var initPos = { x : 0, y : 0 };
var hasMoved = { x : 0, y : 0 };
var hasClicked = false;
var zooming = false;
var layerZoom = false;
var initialCoords = false;
var endCoords = false;

function DimensoesDoMapa() {
}
function DimensoesDoMapa_isAltaResolucao() {
	return ( document.body.clientWidth > 1000 );
}
function DimensoesDoMapa_getLargura() {
	if ( DimensoesDoMapa_isAltaResolucao() )
		return 860;
	else
		return 719;
}
function DimensoesDoMapa_getAltura() {
	if ( DimensoesDoMapa_isAltaResolucao() )
		return 515;
	else
		return 393;
}
DimensoesDoMapa.getLargura = DimensoesDoMapa_getLargura;
DimensoesDoMapa.getAltura = DimensoesDoMapa_getAltura;
DimensoesDoMapa.isAltaResolucao = DimensoesDoMapa_isAltaResolucao;

var SETA = -1;

var ULTIMAS_COORDENADAS =  { latitude: 0, longitude: 0 };

var MAPA_CARREGADO = false;

var TOTAL_NIVES_ZOOM = 15; // 0 a 14
var ZOOM_ATUAL = 10;
var ZOOM_PERMITIDO_PARA_CATEGORIAS = 5;

var TIPO_MAPA_ATUAL = 1;

var ESCONDER_TODOS_ESTABELECIMENTOS = true;
var MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS = false;

var ESTABELECIMENTO_ATUAL = -1;
var ULTIMO_P_ID = -1;

function setEstabelecimentoAtual( id ) { ESTABELECIMENTO_ATUAL = id; }
function getEstabelecimentoAtual() { return ESTABELECIMENTO_ATUAL; }

var ULTIMA_CATEGORIA = "";

var EXIBIR_AUTOMATICAMENTE_PUBLICIDADES = false;
var PODE_RESETAR_MAX_BB = true;

var ATUALIZAR_IMAGEM = false;

var MAX_BB = null;

function mapas( id ) { return document.getElementById ? document.getElementById( id ) : eval( "document.all["+id+"]" ); }

function mostra( elemento ) { mostraObjeto( mapas(elemento) ); }
function esconde( elemento ) { escondeObjeto( mapas(elemento) ) }
function mostraObjeto( objeto ) {
	if ( objeto != undefined )
		objeto.style.display = "block";
}
function escondeObjeto( objeto ) {
	if ( objeto != undefined )
		objeto.style.display = "none";
}
function mostraObjetoVisibility( objeto ) {
	if ( objeto != undefined )
		objeto.style.visibility = "visible";
}
function escondeObjetoVisibility( objeto ) {
	if ( objeto != undefined )
		objeto.style.visibility = "hidden";
}

function mostraElementos( ids, exibirApenas ) {
	var elementoTitulo = null;
	var mostrarTitulo = false;
	var elementos = getElementsById( ids );
	for ( var i=0 ; i<elementos.length ; i++ ) {
		if ( exibirApenas != undefined ) {
			if ( contem(exibirApenas.split(','), elementos[i].getAttribute("publicidadeId")) ) {
				mostraObjeto( elementos[i] );
				mostrarTitulo = true;
			}
			if ( elementos[i].getAttribute("publicidadeId") == "titulo" )
				elementoTitulo = elementos[i]
		} else {
			mostraObjeto( elementos[i] );
		}
	}
	if ( mostrarTitulo == true && elementoTitulo != null )
		mostraObjeto( elementoTitulo );
}
function escondeElementos( ids ) {
	var elementos = getElementsById( ids );
	for ( var i=0 ; i<elementos.length ; i++ )
		escondeObjeto( elementos[i] );
}
function mostraElementosVisibility( ids ) {
	var elementos = getElementsById( ids );
	for ( var i=0 ; i<elementos.length ; i++ )
		mostraObjetoVisibility( elementos[i] );
}
function escondeElementosVisibility( ids ) {
	var elementos = getElementsById( ids );
	for ( var i=0 ; i<elementos.length ; i++ )
		escondeObjetoVisibility( elementos[i] );
}

function endsWithNumero( str ) {
	return str.toLowerCase().match( /^.+((\d))$/gi ) ? true : false;
}

function trim( str ) {
	return str.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

function vazio( str ) {
	return ( trim(str) == "" );
}

function getElementsById( sId ) {
	var outArray = new Array();	
	if ( typeof(sId) != "string" || !sId )
		return outArray;
	if ( document.evaluate ) {
		var xpathString = "//*[@id='"+sId.toString()+"']";
		var xpathResult = document.evaluate( xpathString, document, null, 0, null );
		while ( outArray[outArray.length] = xpathResult.iterateNext() );
		outArray.pop();
	} else if ( document.all && document.all[sId] != undefined ) {
		for( var i=0,j=document.all[sId].length ; i<j ; i+=1 )
			outArray[i] =  document.all[sId][i];
	} else if ( document.getElementsByTagName ) {
		var aEl = document.getElementsByTagName( "*" );	
		for ( var i=0,j=aEl.length ; i<j ; i+=1 )
			if ( aEl[i].id == sId )
				outArray.push(aEl[i]);
	}
	return outArray;
}

function getRequestAJAX() {
	if ( window.XMLHttpRequest )
		return new XMLHttpRequest();
	else if ( window.ActiveXObject )
		return new ActiveXObject( "Microsoft.XMLHTTP" );
	else {
		alert( "Seu browser n\xE3o suporta AJAX!" );
		return null;
	}
}

function contem( array, valor ) {
	for ( var i=0 ; i<array.length ; i++ )
		if ( array[i] == valor )
			return true;
	return false;
}

function carregando() { alert( "Carregando o mapa. Aguarde..." ); }

function mapaOK() {
	return (
		mapObj != undefined
	);
}

function categoriaMarcada_estabelecimentos( categoriaMarcada ) {
	return (
		categoriaMarcada != undefined &&
		categoriaMarcada.estabelecimentos != undefined
	);
}

function document_estabelecimentos() {
	return (
		document != undefined &&
		document.estabelecimentos != undefined
	);
}

// ###########################################################################################################################################

function mudaUF( n, tipo ) {
	cls();
	var UF = jQuery("select#uf"+(tipo==1?"Buscar":"Tracar")).val();
	var url = "http://www.hagah.com.br/mapas/jsp/cidades.jsp?uf="+UF;
	var ajax = getRequestAJAX();
	if ( ajax != null ) {
		ajax.open( "GET", url, false );
		ajax.send( null );
		if ( ajax.readyState == 4 ) {
			if ( ajax.status == 200 ) {
				var cidadeN;
				if ( tipo == 2 || tipo == 3 ) {
					cidadeN = document.getElementById('cidadeTracar');
					jQuery("input#enderecoTracar1").val("");
					jQuery("input#enderecoTracar2").val("");
				} else {
					cidadeN = document.getElementById('cidadeBuscar');
					jQuery("input#enderecoBuscar1").val("");
				}
				var cidades = ajax.responseXML.getElementsByTagName( "cidade" );
				var nome, rotasDisponiveis, exibirCategorias, exibirPublicidades, permitirBuscaSemVirgula;
				for ( var i=0 ; i<cidades.length ; i++ ) {
					nome = cidades[i].getAttribute( "nome" );
					rotasDisponiveis = cidades[i].getAttribute( "rotasDisponiveis" );
					exibirCategorias = cidades[i].getAttribute( "exibirCategorias" );
					exibirPublicidades = cidades[i].getAttribute( "exibirPublicidades" );
					permitirBuscaSemVirgula = cidades[i].getAttribute( "permitirBuscaSemVirgula" );
					cidadeN.options[i] = new Option( nome, nome );
					if ( tipo == 2 )
						cidadeN.options[i].setAttribute( "rotasDisponiveis", rotasDisponiveis );
					if ( cidadePadrao(nome, UF) )
						cidadeN.options[i].selected = true;
					cidadeN.options[i].setAttribute( "exibirCategorias", exibirCategorias );
					cidadeN.options[i].setAttribute( "exibirPublicidades", exibirPublicidades );
					cidadeN.options[i].setAttribute( "permitirBuscaSemVirgula", permitirBuscaSemVirgula );
				}
				cidadeN.options.length = cidades.length;
				if ( tipo == 2 )
					atualizaRotasDisponiveis( cidadeN );
			} else {
				alert( "Erro ("+ajax.status+")." );					
			}
		}
	}
	gravaCookiesCidades( tipo );
	verificaCidade( tipo );
	verificaUF( tipo );
	mostraEscondePublicidades(tipo);
}

function verificaUF( tipo ) {
	/*
	if ( isUtilizarLogoNormal(document.searchMaps.uf1) && isUtilizarLogoNormal(document.searchMaps.uf2) )
		$( "logo" ).src = "../icon/mapas_logo2_"+tipo+".gif";
	else
		$( "logo" ).src = "../icon/mapas_logo2_beta.gif";
	*/
}

function isUtilizarLogoNormal( uf ) {
	if ( uf == undefined )
		return true;
	else if ( uf.selectedIndex >= 0 )
		return uf.options[uf.selectedIndex].value == "RS" || uf.options[uf.selectedIndex].value == "SC";
	else
		return false;
}

function mudaCidade( tipo ) {
	jQuery("input#endereco"+(tipo==1?"Buscar1":"Tracar1")).val("");
	if ( tipo == 2 || tipo == 3 )
		jQuery("input#enderecoTracar2").val("");
	
	gravaCookiesCidades();
	cls();
	verificaCidade( tipo );
	mostraEscondePublicidades(tipo);
	EXIBIR_AUTOMATICAMENTE_PUBLICIDADES = true;
	exibeAutomaticamentePublicidades();
}

function getUFAtual() {
	with( document.searchMaps ) {
		if ( uf1.selectedIndex >= 0 )
			return uf1.options[uf1.selectedIndex].value;
		else
			return "";
	}
}

function gravaCookiesCidades() {
	with( document.searchMaps ) {
		if ( uf1.selectedIndex >= 0 )
			cookiesHagahMapas.setCookie( "hagah.mapas:ultimoUF1", uf1.options[uf1.selectedIndex].value );
		if ( cidade1.selectedIndex >= 0 )
			cookiesHagahMapas.setCookie( "hagah.mapas:ultimoCidade1", cidade1.options[cidade1.selectedIndex].value );
		if ( document.searchMaps.uf2 != undefined )
			if ( uf2.selectedIndex >= 0 )
				cookiesHagahMapas.setCookie( "hagah.mapas:ultimoUF2", uf2.options[uf2.selectedIndex].value );
		if ( document.searchMaps.cidade2 != undefined )
			if ( cidade2.selectedIndex >= 0 )
				cookiesHagahMapas.setCookie( "hagah.mapas:ultimoCidade2", cidade2.options[cidade2.selectedIndex].value );
	}
}

function gravaCookiesCidades( tipo ) {
		cookiesHagahMapas.setCookie( "hagah.mapas:ultimoUF1", jQuery("select#uf"+(tipo == 1?"Buscar":"Tracar")).val() );
		cookiesHagahMapas.setCookie( "hagah.mapas:ultimoCidade1", jQuery("select#cidade"+(tipo == 1?"Buscar":"Tracar")).val() );
		cookiesHagahMapas.setCookie( "hagah.mapas:ultimoUF2", jQuery("select#uf"+(tipo == 1?"Buscar":"Tracar")).val() );
		cookiesHagahMapas.setCookie( "hagah.mapas:ultimoCidade2",jQuery("select#cidade"+(tipo == 1?"Buscar":"Tracar")).val() );
}

function ultimoUFValido( ultimoUF, n ) {
	var UF = eval( "document.searchMaps.uf"+n );
	if ( UF != undefined ) {
		for ( var i=0 ; i < UF.options.length ; i++ )
			if ( UF.options[i].value == ultimoUF )
				return ultimoUF;
			return UF.value;
	}
	return "RS";
}

function ultimaCidadeValida( ultimaCidade, n ) {
	var cidade = eval( "document.searchMaps.cidade"+n );
	if ( cidade != undefined ) {
		for ( var i=0 ; i < cidade.options.length ; i++ )
			if ( cidade.options[i].value == ultimaCidade )
				return ultimaCidade;
			return cidade.value;
	}
	return "Porto Alegre";
}

function recuperaCidades( tipo, ignorarCokieUF1, ignorarCokieCidade1, ignorarCokieUF2, ignorarCokieCidade2 ) {
	with( document.searchMaps ) {
		var suf = jQuery("select#uf"+((tipo == 1)?"Buscar":"Tracar"));
		
		var ultimoUF1 = ultimoUFValido( cookiesHagahMapas.getCookie("hagah.mapas:ultimoUF1"), 1 );
		if ( ultimoUF1 != "" )
			if ( ultimoUF1 != suf.val() && ! ignorarCokieUF1 ) {
				suf.val(ultimoUF1);
				mudaUF( 1, tipo );
				ATUALIZAR_IMAGEM = true; // exibir a imagem do ultimo estado consultado
			}
		var ultimoCidade1 = ultimaCidadeValida( cookiesHagahMapas.getCookie("hagah.mapas:ultimoCidade1"), 1 );
		if ( ultimoCidade1 != "" && ! ignorarCokieCidade1 ) {
			var cidade = jQuery("select#cidade"+((tipo == 1)?"Buscar":"Tracar"));
			if ( cidade.val() != ultimoCidade1 ) {
				cidade.val(ultimoCidade1);
				atualizaRotasDisponiveis( cidade );
			}
		}
	}
	with( document.searchMaps ) {
		var ultimoUF2 = ultimoUFValido( cookiesHagahMapas.getCookie("hagah.mapas:ultimoUF2"), 2 );
		if ( document.searchMaps.uf2 != undefined )
			if ( ultimoUF2 != "" )
				if ( uf2.value != ultimoUF2 && ! ignorarCokieUF2 ) {
					uf2.value = ultimoUF2;
					mudaUF( 2, tipo );
				}
		var ultimoCidade2 = ultimaCidadeValida( cookiesHagahMapas.getCookie("hagah.mapas:ultimoCidade2"), 2 );
		if ( document.searchMaps.cidade2 != undefined )
			if ( ultimoCidade2 != "" && ! ignorarCokieCidade2 )
				if ( cidade2.value != ultimoCidade2 )
					cidade2.value = ultimoCidade2;
	}
	gravaCookiesCidades();
}
function isExibirCategorias( cidade ) {
	if ( cidade == undefined )
		return true;
	else if ( cidade.selectedIndex >= 0 )
		return cidade.options[cidade.selectedIndex].getAttribute("exibirCategorias") == "true";
	else
		return false;
}
function isExibirRecursos( cidade ) {
	if ( cidade == undefined )
		return true;
	else if ( cidade.selectedIndex >= 0 )
		return cidade.options[cidade.selectedIndex].getAttribute("exibirPublicidades") == "true";
	else
		return false;
}

function isPermitirBuscaSemVirgula( cidade ) {
	if ( cidade != undefined && cidade.selectedIndex >= 0 )
		return cidade.options[cidade.selectedIndex].getAttribute("permitirBuscaSemVirgula") == "true";
	else
		return false;
}

function mostraEscondePublicidades() {
	EXIBIR_AUTOMATICAMENTE_PUBLICIDADES = true;
	var cidade = document.searchMaps.cidade1.options[document.searchMaps.cidade1.selectedIndex];
	var exibirPublicidades = cidade.getAttribute( "exibirPublicidades" );
	escondeElementos( "publicidades" );
	if ( ! vazio(exibirPublicidades) )
		mostraElementos( "publicidades", exibirPublicidades );
}

function mostraEscondePublicidades( tipo ) {
	EXIBIR_AUTOMATICAMENTE_PUBLICIDADES = true;
	var op = "cidade"+(tipo==1?"Buscar":"Tracar");
	var cidade = document.getElementById(op).options[document.getElementById(op).selectedIndex];
	var exibirPublicidades = cidade.getAttribute( "exibirPublicidades" );
	escondeElementos( "publicidades" );
	if ( ! vazio(exibirPublicidades) )
		mostraElementos( "publicidades", exibirPublicidades );
}

function cidadePadrao( nome, UF ) {
	if ( UF == "AC" )
		return nome == "Rio Branco";
	else if ( UF == "AL" )
		return nome == "Maceio";
	else if ( UF == "AM" )
		return nome == "Manaus";
	else if ( UF == "AP" )
		return nome == "Macapa";
	else if ( UF == "BA" )
		return nome == "Salvador";
	else if ( UF == "CE" )
		return nome == "Fortaleza";
	else if ( UF == "DF" )
		return nome == "Brasilia";
	else if ( UF == "ES" )
		return nome == "Vitoria";
	else if ( UF == "GO" )
		return nome == "Goiania";
	else if ( UF == "MA" )
		return nome == "Sao Luis";
	else if ( UF == "MG" )
		return nome == "Belo Horizonte";
	else if ( UF == "MS" )
		return nome == "Campo Grande";
	else if ( UF == "MT" )
		return nome == "Cuiaba";
	else if ( UF == "PA" )
		return nome == "Belem";
	else if ( UF == "PB" )
		return nome == "Joao Pessoa";
	else if ( UF == "PE" )
		return nome == "Recife";
	else if ( UF == "PI" )
		return nome == "Teresina";
	else if ( UF == "PR" )
		return nome == "Curitiba";
	else if ( UF == "RJ" )
		return nome == "Rio de Janeiro";
	else if ( UF == "RN" )
		return nome == "Natal";
	else if ( UF == "RO" )
		return nome == "Porto Velho";
	else if ( UF == "RR" )
		return nome == "Boa Vista";
	else if ( UF == "RS" )
		return nome == "Porto Alegre";
	else if ( UF == "SC" )
		return nome == "Florianópolis";
	else if ( UF == "SE" )
		return nome == "Aracaju";
	else if ( UF == "SP" ) {
		return nome == "S\xE3o Paulo";
	} else if ( UF == "TO" )
		return nome == "Palmas";
	else
		return false;
}

// ##########################################################################################################################################

function cls() {
	esconde( "list1" );
	esconde( "list2" );
	esconde( "list11" );
	esconde( "list21" );
	esconde( "list22" );
}

function setText( tipo, logradouro, n ) {
	document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).value = trim( tipo+" "+logradouro )+", ";
	cls();
	document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).focus();
}

function setText( tipo, logradouro, n, tipoSearch ) {
	document.getElementById('endereco'+(tipoSearch==1?'Buscar1':'Tracar'+n)).value = trim( tipo+" "+logradouro )+", ";
	cls();
	document.getElementById('endereco'+(tipoSearch==1?'Buscar1':'Tracar'+n)).focus();
}

function possuiVirgula( str ) {
	return str.indexOf( "," ) >= 0;
}

function mostrarSugestaoDeRuas( event, endereco, cidade, n, tipo ) {
	var tecla = event.keyCode;
	var end = jQuery("input#endereco"+(tipo==1?"Buscar"+n:"Tracar"+n)).val();
	if ( tecla == 27 || tecla == 9 ) {
		cls();
		jQuery("input#endereco"+(tipo==1?"Buscar"+n:"Tracar"+n)).focus();
	} else {
		if ( endereco.value.length >= 4 ) {
			if ( possuiVirgula(end) ) {
				cls();
			} else if ( isPermitirBuscaSemVirgula( document.getElementById('cidade'+(tipo==1?'Buscar':'Tracar')) ) ) {
				if ( ! endsWithNumero( document.getElementById("endereco"+(tipo==1?"Buscar"+n:"Tracar"+n)).value ) )
					sugestaoDeRuas( n, tipo );
				else
					cls();
			} else {
				sugestaoDeRuas( n, tipo );
			}
		} else {
			cls();
		}
	}
}

var ajaxSugestaoDeRuas = null;
var ultimoEnderecoSugestaoDeRuas = "";

function sugestaoDeRuas( n, tipo ) {
	if ( ajaxSugestaoDeRuas == null ) {
		var u, c, e;
		if ( tipo == 1 ){		
			u = document.getElementById('ufBuscar').value;
			c = document.getElementById('cidadeBuscar').value;
			e = document.getElementById('enderecoBuscar1').value;
		} else if ( tipo == 2 ) {
			u = document.getElementById('ufTracar').value;
			c = document.getElementById('cidadeTracar').value;
			e = document.getElementById('enderecoTracar'+n).value;
		} else if ( tipo == 3 ) {
			u = document.getElementById('ufTracar').value;
			c = document.getElementById('cidadeTracar').value;
			e = document.getElementById('enderecoTracar'+n).value;
		}
		var url = "sugestao_de_ruas.jsp?endereco="+escape( e )+"&cidade="+c+"&estado="+u+"&n="+n+"&tipo="+tipo;
		ajaxSugestaoDeRuas = getRequestAJAX();
		ajaxSugestaoDeRuas.open( "GET", url, true );
		ajaxSugestaoDeRuas.onreadystatechange = function() {
		    if ( ajaxSugestaoDeRuas.readyState == 4 ) {
			    if ( ajaxSugestaoDeRuas.status == 200 ) {
					var op = ajaxSugestaoDeRuas.responseText;
					if ( op != "" ) {
						mostra( "list"+tipo+""+n );
						mapas( "list"+tipo+""+n ).innerHTML = op;
					} else {
						cls();
					}
			    } else {
					alert( "Erro" );
				}
				ajaxSugestaoDeRuas = null;
				e = document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).value;
				if ( ultimoEnderecoSugestaoDeRuas != e )
					if ( e.length >= 4 )
						sugestaoDeRuas( n, tipo );
			}
		}
		ajaxSugestaoDeRuas.send( null );
		ultimoEnderecoSugestaoDeRuas = e;
	}
}

function move( event, n) {	
	if ( n == 1 ) {
		var len = document.searchMaps.endereco1.value.length;
	} else {
		var len = document.searchMaps.endereco2.value.length;
	}
	if ( len > 0 ) {
		var tecla = event.keyCode;
		if ( tecla == 40 ) {
			mapas( "a"+n+"1" ).focus();
		} else if ( tecla == 27 ) {
			esconde( "list"+n );
			eval( "document.searchMaps.endereco"+n ).focus();
		}
	}
}

function move( event, n, tipo ) {
	var len = document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).value.length;
	
	if ( len > 0 ) {
		var tecla = event.keyCode;
		if ( tecla == 40 ) {
			mapas( "a"+n+"1" ).focus();
		} else if ( tecla == 27 ) {
			esconde( "list"+tipo+""+n );
			document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).focus();
		}
	}
}

function moveRow( event, id, n ) {
	var tecla = event.keyCode;
	if ( tecla == 40 && mapas("a"+n+""+(id+1)) != null ) {
		id++;
		mapas( "a"+n+""+id ).focus();
	}
	if ( tecla == 38 ){
		if ( id == 1 ) {
			mapas( "endereco"+n ).focus();
		} else {
			id--;
			mapas( "a"+n+""+id ).focus();
		}
	} else if ( tecla == 27 ) {
		esconde( "list"+n );
		eval( "document.searchMaps.endereco"+n ).focus();
	}
}

function moveRow( event, id, n, tipo ) {
	var tecla = event.keyCode;
	if ( tecla == 40 && mapas("a"+n+""+(id+1)) != null ) {
		id++;
		mapas( "a"+n+""+id ).focus();
	}
	if ( tecla == 38 ){
		if ( id == 1 ) {
			document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).focus();
		} else {
			id--;
			mapas( "a"+n+""+id ).focus();
		}
	} else if ( tecla == 27 ) {
		esconde( "list"+n );
		document.getElementById('endereco'+(tipo==1?'Buscar1':'Tracar'+n)).focus();
	}
}

function getMapBoundingBoxAsArray() {
	return (
		[
			mapObj.getBounds().northwest.latitude,
			mapObj.getBounds().southeast.latitude,
			mapObj.getBounds().northwest.longitude,
			mapObj.getBounds().southeast.longitude
		]
	);
}

// ###########################################################################################################################################

function ClasseHashMap() {
	this.elementos = new Object();

	this.put = function( chave, valor ) {
		this.elementos["_"+chave] = valor;
	}
	this.get = function( chave ) {
		return this.elementos["_"+chave];
	}
	this.remove = function( chave ) {
		this.elementos["_"+chave] = true;
	}
}

function ClasseCategoria( id, buscarPor ) {
	this.id = id;
	this.buscarPor = buscarPor;
	this.estabelecimentos = new Array();

	this.addEstabelecimento = function( valor ) {
		this.estabelecimentos[this.estabelecimentos.length] = valor;
	}
	this.getEstabelecimento = function( i ) {
		return this.estabelecimentos[i];
	}
}

function ClasseEstabelecimento( id, index ) {
	this.id = id;
	this.index = index;
}

var CATEGORIAS_MARCADAS = new ClasseHashMap();

// ###########################################################################################################################################

function areaNaoMapeada(mapa, areaMapeada) {
	return (
		areaMapeada == null || ( 
			areaMapeada != null && (
				mapa.southeast.longitude < areaMapeada.southeast.longitude ||
				mapa.northwest.longitude > areaMapeada.northwest.longitude ||
				mapa.southeast.latitude < areaMapeada.southeast.latitude ||
				mapa.northwest.latitude > areaMapeada.northwest.latitude
			)
		)
	);
}
function refreshIconLayer( coordenadas ) {
	if ( ULTIMAS_COORDENADAS.latitude != mapObj.getCenter().latitude || ULTIMAS_COORDENADAS.longitude != mapObj.getCenter().longitude ) {
		if ( mapaOK() ) {
			if ( document_estabelecimentos() ) {
				if ( areaNaoMapeada(mapObj.getBounds(), MAX_BB) ) {
					with ( document.estabelecimentos ) {
						ULTIMA_CATEGORIA = "";
						for ( j = check.length - 1 ; j >= 0 ; j-- ) {
							if ( check[j].checked == true ) {		// se a categoria estah marcada...
								ESCONDER_TODOS_ESTABELECIMENTOS = false;
								PODE_RESETAR_MAX_BB = false;
								ULTIMA_CATEGORIA = check[j].getAttribute( "buscarPor" )+"_"+check[j].value;
								check[j].click();					// desmarca a categoria
								check[j].click();					// remarca a categoria
							}
						}
					}
					exibeAutomaticamentePublicidades();
				}
			}
			ultimoMarcador = null;
		}
	}
	ULTIMAS_COORDENADAS = { latitude: mapObj.getCenter().latitude, longitude: mapObj.getCenter().longitude };
	if ( MAX_BB == null ) {
		resetMAX_BB();
	} else {
		if ( mapObj.getBounds().southeast.latitude < MAX_BB.southeast.latitude )
			MAX_BB.southeast.latitude = mapObj.getBounds().southeast.latitude;
		if ( mapObj.getBounds().northwest.longitude > MAX_BB.northwest.longitude )
			MAX_BB.northwest.longitude = mapObj.getBounds().northwest.longitude;

		if ( mapObj.getBounds().southeast.longitude < MAX_BB.southeast.longitude )
			MAX_BB.southeast.longitude = mapObj.getBounds().southeast.longitude;
		if ( mapObj.getBounds().northwest.latitude > MAX_BB.northwest.latitude )
			MAX_BB.northwest.latitude = mapObj.getBounds().northwest.latitude;
	}
}

function resetMAX_BB() {
	MAX_BB = {
		southeast: {
			latitude: mapObj.getBounds().southeast.latitude, longitude: mapObj.getBounds().southeast.longitude
		},
		northwest: {
			latitude: mapObj.getBounds().northwest.latitude, longitude: mapObj.getBounds().northwest.longitude
		}
	};
}

function reexibeSeta() {
	if ( SETA > 0 ) {
		mapObj.removeMarker( SETA );
		exibeSeta();	
	}
}

function exibeAutomaticamentePublicidades() {
	if ( EXIBIR_AUTOMATICAMENTE_PUBLICIDADES == true ) {
		if ( ZOOM_ATUAL <= ZOOM_PERMITIDO_PARA_CATEGORIAS ) {
			if ( document_estabelecimentos() ) {
				with ( document.estabelecimentos ) {
					for ( i = check.length - 1 ; i >= 0 ; i-- )
						if ( check[i] != undefined )
							if ( check[i].getAttribute("exibirAutomaticamente") == "true" )
								if ( check[i].parentNode.style.display != "none" ) // se o div ao redor do check estah visivel, este pode ser clicado para exibir os icones no mapa
									if ( ! check[i].checked )
										check[i].click();
				}
			}
		}
		EXIBIR_AUTOMATICAMENTE_PUBLICIDADES = false;
	}
}

function desmarcaIconLayer( uf, local, region ) {
	if ( document_estabelecimentos() ) {
		with ( document.estabelecimentos ) {
			for ( j = 0 ; j < check.length ; j++ )
				if ( check[j].checked == true ) {		// se a categoria estah marcada...
					check[j].checked = false;			// desmarca a categoria
					adicionaIconesNoMapa( null, check[j], uf, local, region );
				}
		}
	}
}

function getParameter(url, name) {
	var expression,
	results;
	
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"),
	expression = new RegExp("[\\?&]"+ name +"=([^&#]*)"),
	results = expression.exec(url),
	
	url = name = expression = null;
	
	return !results ? "" : results[1];
}

function adicionaIconesNoMapa( ajaxResponse, checkClicado, uf, local, region ) {
	if ( checkClicado.checked == true ) {
		var data = ajaxResponse.getElementsByTagName( "lc" );
		
		var categoriaMarcadaAnterior = CATEGORIAS_MARCADAS.get( checkClicado.getAttribute("buscarPor")+"_"+checkClicado.value );
		
		var categoriaMarcada = null;
		if ( categoriaMarcadaAnterior == undefined )
			categoriaMarcada = new ClasseCategoria( checkClicado.value, checkClicado.getAttribute("buscarPor") );
		else
			categoriaMarcada = categoriaMarcadaAnterior;
		
		var id, nome, tipo_log, logradouro, numero, comp_num, bairro, cidade, estado, lat, lon, phone, ex_phone, categoria, cidadeId;
		for( var i = 0 ; i < data.length ; i++ ) {
			id = data[i].getElementsByTagName( "id" ).item( 0 ).firstChild.data;
			nome = data[i].getElementsByTagName( "a" ).item( 0 ).firstChild.data;
			tipo_log = data[i].getElementsByTagName( "b" ).item( 0 ).firstChild.data;
			logradouro = data[i].getElementsByTagName( "c" ).item( 0 ).firstChild.data;
			numero = data[i].getElementsByTagName( "d" ).item( 0 ).firstChild.data;
			comp_num = data[i].getElementsByTagName( "e" ).item( 0 ).firstChild.data;
			bairro = data[i].getElementsByTagName( "f" ).item( 0 ).firstChild.data;
			cidade = data[i].getElementsByTagName( "g" ).item( 0 ).firstChild.data;
			estado = data[i].getElementsByTagName( "h" ).item( 0 ).firstChild.data;
			lat = data[i].getElementsByTagName( "j" ).item( 0 ).firstChild.data;
			lon = data[i].getElementsByTagName( "i" ).item( 0 ).firstChild.data;
			phone = data[i].getElementsByTagName( "k" ).item( 0 ).firstChild.data;
			ex_phone = data[i].getElementsByTagName( "l" ).item( 0 ).firstChild.data;			
			categoria = data[i].getElementsByTagName( "m" ).item( 0 ).firstChild.data;
			cidadeId = data[i].getElementsByTagName( "n" ).item( 0 ).firstChild.data;
			friendlyName = data[i].getElementsByTagName( "o" ).item( 0 ).firstChild.data;
			friendlyCityName = data[i].getElementsByTagName( "p" ).item( 0 ).firstChild.data;

			if ( checkClicado.getAttribute("buscarPor") == "publicidade" ) {
				p_image = "http://hagahguialocal.com.br/mapas/icon/"+checkClicado.getAttribute("icone" );
				p_id = "p"+id;
				p_sizeX = 28;
				p_sizeY = 28;
			} else if ( checkClicado.getAttribute("buscarPor") == "recurso" ) {
				p_image = "http://hagahguialocal.com.br/mapas/icon/"+checkClicado.value+".gif";
				p_id = "r"+id;
				p_sizeX = 22;
				p_sizeY = 22;
			} else {
				p_image = "http://hagahguialocal.com.br/mapas/icon/"+checkClicado.value+".gif";
				p_id = id;
				p_sizeX = 22;
				p_sizeY = 22;
			}

			if ( p_id != ULTIMO_P_ID ) {
				p_latitude = ""+lat;
				p_longitude = ""+lon;
				
				p_maptip = "";
					
				p_maptip += "<h1 style='font-size:12px;color: #728ca3;'>"+nome+"</h1>";
				p_maptip += "<h2 style='font-size:10px;color: #728ca3;'>"+categoria+"</h2><br>";
				p_maptip += "<p align='left'>";
				if ( ( numero != "nd" ) && ( numero != "" ) ) { 					
					if ( ( tipo_log != "nd" ) && ( tipo_log != "" ) ) { 					
						p_maptip += ""+tipo_log+" "+logradouro+", "+numero;					
					} else {
						p_maptip += ""+logradouro+", "+numero;					
					}
				} else {
					p_maptip += ""+tipo_log+" "+logradouro;
				}
				if ( ( comp_num != "nd" ) && ( comp_num != "" ) ) { 
					p_maptip += " - "+comp_num+"<br />";
				} else {
					p_maptip += "<br />";
				}
				if ( ( bairro != "nd" ) && ( bairro != "" ) ) { 
					p_maptip += ""+bairro+"<br />";
				}
				if ( ( cidade != "nd" ) && ( cidade != "" ) ) { 						
					p_maptip += ""+cidade+" - "+estado+"<br />";
				} else {
					p_maptip += ""+estado+"<br />";
				}
				p_maptip += "</p>";
				if ( ( phone != "nd" ) && ( phone != "" ) ) {
					if ( ( ex_phone != "nd" ) && ( ex_phone != "" ) ) {
						p_maptip += "<p align='left'>"+phone+" "+ex_phone+"</p>";
					} else {
						p_maptip += "<p align='left'>"+phone+"</p>";
					}
				}
				var URLLocaisEServicos = "http://www.hagah.com.br/"+estado.toLowerCase()+"/"+friendlyCityName+"/local/"+id+","+friendlyName+".html";
				
				// vale do itajai mostra popup sem guia local
				p_maptip += "<a target='_blank' href='"+URLLocaisEServicos+"' style='font-weight:bold;color:#728ca3;'>";
				p_maptip += "<br>+ informa&ccedil;&otilde;es</a>";
				p_maptip += "</a>";
	
				var markPoint = new aptMarkPoint(
					new aptGeopoint( p_latitude, p_longitude ),
					p_image,
					p_sizeX, p_sizeY,
					{
						title: nome,
						info: p_maptip,
						size: 225,
						override: false
					}
				);
			   	var indexIconePubl = mapObj.addMarker( markPoint );
			   	
				categoriaMarcada.addEstabelecimento( { id: p_id, index: indexIconePubl } );
			}

			if ( categoriaMarcadaAnterior == undefined )
				CATEGORIAS_MARCADAS.put( categoriaMarcada.buscarPor+"_"+categoriaMarcada.id, categoriaMarcada );

		}

		window.status = "Estabelecimentos \""+checkClicado.value+"\" lidos. Total encontrado: "+data.length+".";
		
		if ( ULTIMA_CATEGORIA == checkClicado.getAttribute("buscarPor")+"_"+checkClicado.value )
			esconde( "loading" );

		reexibeSeta();
	} else {
		var categoriaMarcada = CATEGORIAS_MARCADAS.get( checkClicado.getAttribute("buscarPor")+"_"+checkClicado.value );
		
		if ( categoriaMarcada_estabelecimentos(categoriaMarcada) ) {
			for( i = 0 ; i < categoriaMarcada.estabelecimentos.length ; i++ ) {
//				if ( ESCONDER_TODOS_ESTABELECIMENTOS == "true" || categoriaMarcada.estabelecimentos[i].index != getEstabelecimentoAtual() ) {
//					mapObj.removeMarker( categoriaMarcada.estabelecimentos[i].index );
//				}
				if ( ESCONDER_TODOS_ESTABELECIMENTOS == true ) {
					mapObj.removeMarker( categoriaMarcada.estabelecimentos[i].index );
				}
				if ( categoriaMarcada.estabelecimentos[i].index == getEstabelecimentoAtual() ) {
					ULTIMO_P_ID = categoriaMarcada.estabelecimentos[i].id;
				}
			}
			window.status = "Ocultando estabelecimentos \""+checkClicado.value+"\". Total: "+categoriaMarcada.estabelecimentos.length+".";
//			CATEGORIAS_MARCADAS.remove( checkClicado.getAttribute("buscarPor")+"_"+checkClicado.value );
			ESCONDER_TODOS_ESTABELECIMENTOS = true;
		}
		ultimoMarcador = null;
		ULTIMA_CATEGORIA = "";
		ULTIMO_P_ID = -1;
	}
}

function addMarker( latitude, longitude, imagem, largura, altura, title, info ) {
	if ( title == undefined )
		title = "";
	if ( info == undefined )
		info = "";
	var naoAbrirMapTip = false;
	if ( title == "" && info == "" )
		naoAbrirMapTip = true;
	var size = 225;
   	mapObj.addMarker(
		new aptMarkPoint(
			new aptGeopoint( latitude, longitude ),
			imagem,
			largura, altura,
			{
				title: title,
				info: info,
				size: size,
				override: naoAbrirMapTip
			}
		)
	);
}

// ###########################################################################################################################################

function changeTypeMap( tp ) {
	if ( tp == 1 ) {
		mapObj.changeToRaster();
		mapas( "typeMap1" ).setAttribute( "src", "../icon/map_bt_mapa_on.gif" );
		mapas( "typeMap2" ).setAttribute( "src", "../icon/map_bt_hibrido.gif" );
		mapas( "typeMap3" ).setAttribute( "src", "../icon/map_bt_satelite.gif" );		
	} else if ( tp == 2 ) {
		mapObj.changeToHybrid();
		mapas( "typeMap1" ).setAttribute( "src", "../icon/map_bt_mapa.gif" );
		mapas( "typeMap2" ).setAttribute( "src", "../icon/map_bt_hibrido_on.gif" );
		mapas( "typeMap3" ).setAttribute( "src", "../icon/map_bt_satelite.gif" );		
	} else if ( tp == 3 ) {
		mapObj.changeToSatellite();
		mapas( "typeMap1" ).setAttribute( "src", "../icon/map_bt_mapa.gif" );
		mapas( "typeMap2" ).setAttribute( "src", "../icon/map_bt_hibrido.gif" );
		mapas( "typeMap3" ).setAttribute( "src", "../icon/map_bt_satelite_on.gif" );		
	}
	TIPO_MAPA_ATUAL = tp;
}

function changeTypeMapImoveis( tp ) {
	if ( tp == 1 ) {
		mapObj.changeToRaster();
		mapas( "typeMap1" ).setAttribute( "class", "on" );
		mapas( "typeMap2" ).setAttribute( "class", " " );		
		mapas( "typeMap3" ).setAttribute( "class", " " );		
	} else if ( tp == 2 ) {
		mapObj.changeToHybrid();	
		mapas( "typeMap1" ).setAttribute( "class", " " );
		mapas( "typeMap2" ).setAttribute( "class", "on" );		
		mapas( "typeMap3" ).setAttribute( "class", " " );		
	} else if ( tp == 3 ) {
		mapObj.changeToSatellite();
		mapas( "typeMap1" ).setAttribute( "class", " " );
		mapas( "typeMap2" ).setAttribute( "class", " " );		
		mapas( "typeMap3" ).setAttribute( "class", "on" );			
	}
	TIPO_MAPA_ATUAL = tp;
}

function dragAndDropMap() {	
	mapas( "dADMap" ).setAttribute( "src", "../icon/map_bt_hand_on.gif" );
	mapas( "zIMap" ).setAttribute( "src", "../icon/map_bt_zoomarea.gif" );
	mapas( "zoMap" ).setAttribute( "src", "../icon/map_bt_zoom_out.gif" );
	if ( mapaOK() ) {
		mapObj.registerListener( refreshIconLayer, "stopmove" );
		deactivateSquareZooming();
	}
}

function dragAndDropMapImoveis() {	
	mapas( "dADMap" ).setAttribute( "class", "on" );
	mapas( "zIMap" ).setAttribute( "class", " " );
	mapas( "zoMap" ).setAttribute( "class", " " );
	if ( mapaOK() ) {
		mapObj.registerListener( refreshIconLayer, "stopmove" );
		deactivateSquareZooming();
	}
}

function zoomOutMap() {
	MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS = false;
	mapas( "dADMap" ).setAttribute( "src", "../icon/map_bt_hand.gif" );
	mapas( "zIMap" ).setAttribute( "src", "../icon/map_bt_zoomarea.gif" );
	mapas( "zoMap" ).setAttribute( "src", "../icon/map_bt_zoom_out_over.gif" );
	if ( mapaOK() ) {
		zoomOutMapCallback = function( coordenadas ) {
			if ( ZOOM_ATUAL < TOTAL_NIVES_ZOOM - 1)
		    	centerMap( coordenadas.latitude, coordenadas.longitude, mapObj.getZoom() + 1 );
			else
				alert( "N\xE3o \xE9 poss\xEDvel afastar mais." );
		}
		mapObj.registerListener( zoomOutMapCallback, "stopmove" );
		deactivateSquareZooming();
	}
}

function zoomOutMapImoveis() {
	MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS = false;
	mapas( "dADMap" ).setAttribute( "class", " " );
	mapas( "zIMap" ).setAttribute( "class", " " );
	mapas( "zoMap" ).setAttribute( "class", "on" );
	if ( mapaOK() ) {
		zoomOutMapCallback = function( coordenadas ) {
			if ( ZOOM_ATUAL < TOTAL_NIVES_ZOOM - 1)
		    	centerMap( coordenadas.latitude, coordenadas.longitude, mapObj.getZoom() + 1 );
			else
				alert( "N\xE3o \xE9 poss\xEDvel afastar mais." );
		}
		mapObj.registerListener( zoomOutMapCallback, "stopmove" );
		deactivateSquareZooming();
	}
}

function zoomInMap() {
	mapas( "dADMap" ).setAttribute( "src", "../icon/map_bt_hand.gif" );
	mapas( "zIMap" ).setAttribute( "src", "../icon/map_bt_zoomarea_over.gif" );
	mapas( "zoMap" ).setAttribute( "src", "../icon/map_bt_zoom_out.gif" );
	if ( mapaOK() ) {
		activateSquareZooming();
	}
}

function zoomInMapImoveis() {
	mapas( "dADMap" ).setAttribute( "class", " " );
	mapas( "zIMap" ).setAttribute( "class", "on" );
	mapas( "zoMap" ).setAttribute( "class", " " );
	if ( mapaOK() ) {
		activateSquareZooming();
	}
}

function deactivateSquareZooming() {
	mapObj.setListenersOn();
//	mapObj.removeLayer(layerZoom.uid);
	zooming = false;
}

function activateSquareZooming() {
	mapObj.setListenersOff();

	mapObj.registerListener(onclickListener, "leftclick");
	mapObj.registerListener(onmoveListener, "mousemove");
	mapObj.registerListener(onstopListener, "stopmove");

	layerZoom = mapObj.addLayer();

	layerZoom.style.fontSize = "1px"; // necessário para correção de tamanho no IE
	layerZoom.style.position = "absolute";

	zooming = true;
}

/*
function onclickListener(coords, e) {
	if(zooming) {
		initPos.x = mapObj.remXoffset(e.clientX);
		initPos.y = mapObj.remYoffset(e.clientY);

		layerZoom.style.top = initPos.y + 'px';
		layerZoom.style.left = initPos.x + 'px';
		layerZoom.style.border = "1px solid #990000";

		hasClicked = true;
		initialCoords = coords;
	}
}

function onmoveListener(coords, e) {
	if ( hasClicked && zooming ) {
		hasMoved.x = e.clientX - initPos.x;
		hasMoved.y = e.clientY - initPos.y;

		if(hasMoved.x > 0)
			layerZoom.style.width = hasMoved.x + 'px';	
		else {
			layerZoom.style.width = -(hasMoved.x) + 'px';
			layerZoom.style.left = e.clientX + 'px';
		}

		if(hasMoved.y > 0)
			layerZoom.style.height = hasMoved.y + 'px';	
		else {
			layerZoom.style.height = - hasMoved.y + 'px';
			layerZoom.style.top = e.clientY + 'px';
		}
	}
}
*/

onclickListener = function(coords, e) {
	if(zooming) {
	
		initPos.x = mapObj.remXoffset(e.clientX);
		initPos.y = mapObj.remYoffset(e.clientY);
		
		initPos.y = initPos.y + (mapObj.mashup.page.getScrollY() * 2);
		initPos.x = initPos.x + (mapObj.mashup.page.getScrollX() * 2);
	
		layerZoom.style.top = initPos.y + 'px';
		layerZoom.style.left = initPos.x + 'px';
		layerZoom.style.border = "2px solid black";
		
		hasClicked = true;
		initialCoords = coords;
		
	}
}

onmoveListener = function(coords, e) {
	if(hasClicked && zooming) {
		var cX = mapObj.remXoffset(e.clientX) + (mapObj.mashup.page.getScrollX() * 2);
		var cY = mapObj.remYoffset(e.clientY) + (mapObj.mashup.page.getScrollY() * 2);

		hasMoved.x = cX - initPos.x;
		hasMoved.y = cY - initPos.y;
		
		//hasMoved.y = hasMoved.y + (mapObj.mashup.page.getScrollY() * 2);
		
		if(hasMoved.x > 0){
			layerZoom.style.width = hasMoved.x + 'px';	
		}else {
			layerZoom.style.width = -(hasMoved.x) + 'px';
			layerZoom.style.left = cX + 'px';
		}
		
		if(hasMoved.y > 0){
			layerZoom.style.height = hasMoved.y + 'px';
		}else {
			layerZoom.style.height = -(hasMoved.y) + 'px';
			layerZoom.style.top = cY + 'px';
		}
	}
}
function onstopListener(coords, e) {
	if(zooming) {
		hasClicked = false;
		endCoords = coords;

		north = Math.max(endCoords.lat(), initialCoords.lat());
		south = Math.min(endCoords.lat(), initialCoords.lat());

		east = Math.max(endCoords.lon(), initialCoords.lon());
		west = Math.min(endCoords.lon(), initialCoords.lon());

		northwest = new aptGeopoint(north, west);
		southeast = new aptGeopoint(south, east);

		mapObj.setBounds(northwest, southeast);
		layerZoom.style.border = "none";
		layerZoom.style.height = "0px";
		layerZoom.style.width = "0px";
		
		var z = mapObj.getZoom();
		zoomCurrent( mapas("z"+z), z );
	}
}
function centerMap( latitude, longitude, z ) {
	if ( mapaOK() ) {
		mapObj.centerAndZoom( new aptGeopoint(latitude, longitude), z );
		zoomCurrent( mapas("z"+z), z );
	}
}

function janelaPopup( caminho, largura, altura ) {
	largura = largura == undefined ? 700 : largura;
	altura = altura == undefined ? 700 : altura;
	window.open( caminho, "", "scrollbars=0,width="+largura+",height="+altura+",statusbar=0" );
}

function janelaPopupScroll( caminho, largura, altura ) {
	largura = largura == undefined ? 700 : largura;
	altura = altura == undefined ? 700 : altura;
	window.open( caminho, "", "scrollbars=1,width="+largura+",height="+altura+",statusbar=0" );
}

function insiraEmSeuSite( uf, local, regionId, uf1, cidade1, endereco1 ) {
	if ( mapaOK() ) {
		var url = ""+
			"http://www.hagah.com.br/widgets/mapas/personaliza.html?"+
			"uf="+uf+"&"+
			"local="+local+"&"+
			"regionId="+regionId+"&"+
			"uf1="+uf1+"&"+
			"cidade1="+cidade1+"&"+
			"endereco1="+endereco1+"&"+
			"mapaAtual="+escape( getImagemMapa() )
		;
		janelaPopupScroll( url, 525, 725 );
	} else {
		carregando();
	}
} 

function getImagemMapa() {
	var bb = getMapBoundingBoxAsArray();
	return ""+
		"http://mapas.hagah.com.br/rbs/wgmap/image2_rbs_proxy.php?"+
		"servid=&"+
		"url=&"+
		"wgs84x1y1="+bb[0]+"|"+bb[2]+"&"+
		"wgs84x2y2="+bb[1]+"|"+bb[3]+"&"+
		"w="+DimensoesDoMapa.getLargura()+"&"+
		"h="+DimensoesDoMapa.getAltura()
	;
}

function printMapSomenteEstado( uf, resolucaoAlta ) {
	if ( mapaOK() ) {
		var bbox = getMapBoundingBoxAsArray();
		if ( TIPO_MAPA_ATUAL != 1 )
			changeTypeMap( 1 );
		var consulta = ""+
			"buscar=false&"+
			"uf="+uf+"&"+
			"uf1="+getUFAtual()+"&"+
			"resolucaoAlta="+resolucaoAlta+"&"+
			"lat0="+bbox[0]+"&"+
			"lat1="+bbox[1]+"&"+
			"long0="+bbox[2]+"&"+
			"long1="+bbox[3]
		;
		janelaPopupScroll( "popup_imprimir.jsp?"+consulta );
	} else {
		carregando();
	}
}

function printMap( uf, id1, uf1, cidade1, endereco1, id2, uf2, cidade2, endereco2, tp, transportmode, toll, resolucaoAlta ) {
	if ( mapaOK() ) {
		var bbox = getMapBoundingBoxAsArray();
		if ( TIPO_MAPA_ATUAL != 1 )
			changeTypeMap( 1 );
		var consulta = ""+
			"buscar=true&"+
			"uf="+uf+"&"+
			"id1="+id1+"&"+
			"uf1="+uf1+"&"+
			"cidade1="+cidade1+"&"+
			"endereco1="+endereco1+"&"+
			"id2="+id2+"&"+
			"uf2="+uf2+"&"+
			"cidade2="+cidade2+"&"+
			"endereco2="+endereco2+"&"+
			"type="+tp+"&"+
			"transportmode="+transportmode+"&"+
			"toll="+toll+"&"+
			"resolucaoAlta="+resolucaoAlta+"&"+
			"lat0="+bbox[0]+"&"+
			"lat1="+bbox[1]+"&"+
			"long0="+bbox[2]+"&"+
			"long1="+bbox[3]
		;
		janelaPopupScroll( "popup_imprimir.jsp?"+consulta );
	} else {
		carregando();
	}
}

/** Pop-up de enviar para amigo.
 */
function sendFriendMap( uf, id1, uf1, cidade1, endereco1, id2, uf2, cidade2, endereco2, tp, transportmode, toll, resolucaoAlta ) {
	if ( mapaOK() ) {
		var bbox = getMapBoundingBoxAsArray();
		if ( TIPO_MAPA_ATUAL != "1" )
			changeTypeMap( "1" );
		var consulta = window.location.href;
		var url = ""+
			"popup_envie_form.jsp?"+
			"uf="+uf+"&"+
			"originsite=mapas&"+
			"url_print=&"+
			"mapaAtual="+escape( "?" )+"&"+
			"consulta="+escape( consulta )+"&"+
			"beta="+( ! isUtilizarLogoNormal(document.searchMaps.uf1) || ! isUtilizarLogoNormal(document.searchMaps.uf2) )+"&"+
			"lat0="+bbox[0]+"&"+
			"lat1="+bbox[1]+"&"+
			"long0="+bbox[2]+"&"+
			"long1="+bbox[3]
		;
		janelaPopup( url, 550, 375 );
	} else {
		carregando();
	}
}

function informarErro() {
	var urlAtual = parent.window.location.href;
	var url = ""+
		"http://www.clicrbs.com.br/atendimento/jsp/default.jsp?"+
		"template=2855.dwt&"+
		"newsID=DYNAMIC,atendimento.AtendimentoDataServer,getFaleConosco&idcentral=191&"+
		"logo=hagah&"+
		"dominio=hagah&"+
		"destinatario=Informar%20erro%23%25%23atendimento@hagah.com.br%23%25%23Hagah_mapa&"+
		"urlAtual="+escape( urlAtual );
	;
	janelaPopupScroll( url, 656, 520 );
}

/** Deslocamentos do mapa.
 */
function pan( direcao ) {
	// alert( direcao );
	var bbox = getMapBoundingBoxAsArray();
	// alert( bbox[0]+", "+bbox[1]+", "+bbox[2]+", "+bbox[3] )
	if ( mapaOK() ) {
		if ( direcao == "n" )
			mapObj.setCenter( new aptGeopoint( bbox[0] - (bbox[1] - bbox[0])/100.0, (bbox[3] + bbox[2])/2.0) );
			// mapObj.moveMapBy( 0, - mapObj.map.height/2 );
		else if ( direcao == "w" )
			mapObj.setCenter( new aptGeopoint( (bbox[1] + bbox[0])/2.0, bbox[2] - (bbox[3] - bbox[2])/100.0) );
			// mapObj.moveMapBy( - mapObj.map.width/2, 0 );
		else if ( direcao == "s" )
			mapObj.setCenter( new aptGeopoint( bbox[1] + (bbox[1] - bbox[0])/100.0, (bbox[3] + bbox[2])/2.0) );
			// mapObj.moveMapBy( 0, mapObj.map.height/2 );
		else if ( direcao == "e" )
			mapObj.setCenter( new aptGeopoint( (bbox[1] + bbox[0])/2.0, bbox[3] + (bbox[3] - bbox[2])/100.0) );
			// mapObj.moveMapBy( mapObj.map.width/2, 0 );
		else if ( direcao == "nw" )
			mapObj.setCenter( new aptGeopoint(bbox[0], bbox[2]) );
			// mapObj.moveMapBy( - mapObj.map.width/2, - mapObj.map.height/2 );
		else if ( direcao == "ne" )
			mapObj.setCenter( new aptGeopoint(bbox[0], bbox[3]) );
			// mapObj.moveMapBy( mapObj.map.width/2, - mapObj.map.height/2 );
		else if ( direcao == "sw" )
			mapObj.setCenter( new aptGeopoint(bbox[1], bbox[2]) );
			// mapObj.moveMapBy( - mapObj.map.width/2, mapObj.map.height/2 );
		else if ( direcao == "se" )
			mapObj.setCenter( new aptGeopoint(bbox[1], bbox[3]) );
			// mapObj.moveMapBy( mapObj.map.width/2, mapObj.map.height/2 );
		setTimeout( "refreshIconLayer()", 1000 );
	}
}

function atualizaRotasDisponiveis( s, naoMarcarCarro ) {
	if ( s.selectedIndex >= 0 ) {
		var o = s.options[s.selectedIndex];
		var rotasDisponiveis = o.getAttribute( "rotasDisponiveis" );
		if ( rotasDisponiveis == "2,3" ) {
			jQuery("input#tranportmodeTracar1").disabled = false;
			if ( naoMarcarCarro != false )
				jQuery("input#tranportmodeTracar1").checked = true;
			//jQuery("input#tranportmodeTracar1").nextSibling.className = "";
			jQuery("input#tranportmodeTracar2").disabled = false;
		} else if ( rotasDisponiveis == "2" ) {
			jQuery("input#tranportmodeTracar1").disabled = false;
			//jQuery("input#tranportmodeTracar1").nextSibling.className = "";
			jQuery("input#tranportmodeTracar2").disabled = false;
		} else if ( rotasDisponiveis == "3" ) {
			jQuery("input#tranportmodeTracar1").disabled = true;
			//jQuery("input#tranportmodeTracar1").nextSibling.className = "rota-disabled";
			jQuery("input#tranportmodeTracar2").disabled = false;
			jQuery("input#tranportmodeTracar2").checked = true;
		}
	}
}

function atualizaRotasDisponiveisIframe( s, naoMarcarCarro ) {
	if ( s.selectedIndex >= 0 ) {
		var o = s.options[s.selectedIndex];
		var rotasDisponiveis = o.getAttribute( "rotasDisponiveis" );
		with( parent.document.searchMaps ) {
			if ( rotasDisponiveis == "2,3" ) {
				transportmode[0].disabled = false;
				if ( naoMarcarCarro != false )
					transportmode[0].checked = true;
				transportmode[0].nextSibling.className = "";
				transportmode[1].disabled = false;
			} else if ( rotasDisponiveis == "2" ) {
				transportmode[0].disabled = false;
				transportmode[0].nextSibling.className = "";
				transportmode[1].disabled = false;
			} else if ( rotasDisponiveis == "3" ) {
				transportmode[0].disabled = true;
				transportmode[0].nextSibling.className = "rota-disabled";
				transportmode[1].disabled = false;
				transportmode[1].checked = true;
			}
		}
	}
}

function controleDoMapa( chamada ) {
	if ( mapaOK() )
		eval( chamada );
	else
		carregando();
}

function OAS_AD_Right() {
	document.write( "<div id=\"button_banner\">" );
	document.write(		"<div style=\"padding-top: 6px;\">" );
	OAS_AD( "Right" );
	document.write( 	"</div>" );
	document.write( "</div>" );
}

///////////////////////////////// BARRA DE CONTROLE DO ZOOM /////////////////////////////////
	function zoomCurrent( elementoClicado, nivel, atualizar ) {
		ZOOM_ATUAL = nivel;
		if ( atualizar == true || atualizar == undefined )
			zoom( ZOOM_ATUAL );
		for ( i=0 ; i < nivel ; i++ )
			mapas( "z"+i ).className = "ZoomStep"+( i==TOTAL_NIVES_ZOOM - 1?"Left":"" );
		elementoClicado.className = "ZoomStep"+( i==TOTAL_NIVES_ZOOM - 1?"Left":"" )+" CurrentRight";
		for ( i++ ; i < TOTAL_NIVES_ZOOM ; i++ )
			mapas( "z"+i ).className = "ZoomStep"+( i==TOTAL_NIVES_ZOOM - 1?"Left":"" )+" Current";
	}
	function zoom( nivel ) {
		if ( mapaOK() ) {
			MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS = false;
			mapObj.zoomCenter( nivel );
			refreshIconLayer();
		}
	}

	function zoomIn() {
		if ( mapaOK() ) {
			if ( ZOOM_ATUAL > 0 ) {
				ZOOM_ATUAL--;
				zoomCurrent( mapas("z"+ZOOM_ATUAL), ZOOM_ATUAL, true );
			} else {
				alert( "N\xE3o \xE9 poss\xEDvel aproximar mais." );
			}
		}
	}
	function zoomOut() {
		if ( mapaOK() ) {
			if ( ZOOM_ATUAL < TOTAL_NIVES_ZOOM - 1 ) {
				ZOOM_ATUAL++;
				zoomCurrent( mapas("z"+ZOOM_ATUAL), ZOOM_ATUAL, true );
			} else {
				alert( "N\xE3o \xE9 poss\xEDvel afastar mais." );
			}
		}
	}

	function mOver( s ) {
		s.style.cursor = "pointer";
	}
	function mOut( s ) {
		s.style.cursor = "auto";
	}
///////////////////////////////// /BARRA DE CONTROLE DO ZOOM /////////////////////////////////

////////////////////////////////////////// COOKIES ///////////////////////////////////////////
function Cookies( dias ) {
	this.dias = dias;
	this.setCookie = function( nome, valor, dias ) {
		var cookieString = nome+"="+escape( valor )+";";
		if ( dias == undefined  )
			dias = this.dias;
		if ( dias > 0 )
			cookieString += "EXPIRES="+getDataVencimento( dias )+";";
		cookieString += "path=/;";
		document.cookie = cookieString;
	}
	this.getCookie = function( cookieName ) {
		var cookieString = document.cookie+"";
		var index1 = cookieString.indexOf( cookieName+"=" );
		if ( index1 == -1 || cookieName == "" )
			return ""; 
		var index2 = cookieString.indexOf( ";", index1 );
		if ( index2 == -1 )
			index2 = cookieString.length; 
		return unescape( cookieString.substring(index1 + cookieName.length + 1, index2) );
	}
	function getDataVencimento( dias ) {
		var UTCstring;
		var hoje = new Date();
		var ms = Date.parse( hoje );
		hoje.setTime( ms + dias*24*60*60*1000 );
		return hoje.toUTCString();
	}
}
var cookiesHagahMapas = new Cookies( 365 );
///////////////////////////////////////// /COOKIES ///////////////////////////////////////////

function removeCategorias(t){
	esconde( "map_navigation_b" );
	if ( t == 2 && mapas("subcontent_detail") != null ) {
		mapas( "subcontent_detail" ).style.width = "97.5%";
		mapas( "subcontent_detail" ).style.marginRight = "0px";
		mapas( "subcontent_detail" ).style.paddingRight = "10px";
	}
}

function verificaCidade( tp ){
	if ( tp == null )
		tp = 1;
	
	var cid2;
	if ( tp == 3 )
		cid2 = jQuery("select#cidadeTracar").val();
	if ( tp == 1 && !isExibirCategorias(jQuery("select#cidadeBuscar")) ) {
		removeCategorias( 1 );
	} else if ( tp == 2 && !isExibirCategorias(jQuery("select#cidadeTracar")) ) {
		removeCategorias( 2 );
	} else if ( tp == 3 && (!isExibirCategorias(jQuery("select#cidadeTracar")) || !isExibirCategorias(jQuery("select#cidadeTracar"))) ) {
		removeCategorias( 2 );
	} else {		
		mostra( "map_navigation_b" );
		if ( mapas("subcontent_detail") != null  ) {
			if ( DimensoesDoMapa.isAltaResolucao() )
				mapas( "subcontent_detail" ).style.width = "520px";
			else
				mapas( "subcontent_detail" ).style.width = "430px";
			mapas( "subcontent_detail" ).style.marginRight = "8px";
			mapas( "subcontent_detail" ).style.paddingRight = "3px";
		}
	}
}

function buscaEstabelecimentos( checkClicado, uf, local, region ) {
	ULTIMA_CATEGORIA = checkClicado.getAttribute( "buscarPor" )+"_"+checkClicado.value;
	if ( checkClicado.checked == true ) {
		if ( ZOOM_ATUAL <= ZOOM_PERMITIDO_PARA_CATEGORIAS ) { // exibir os estabelecimentos da categoria ou publicidade "checkClicado.value"
			if ( mapaOK() ) {
				if ( PODE_RESETAR_MAX_BB ) {
					resetMAX_BB();
				} else {
					PODE_RESETAR_MAX_BB = true;
				}				
				mostra( "loading" );
				window.status = "Iniciando leitura dos estabelecimentos \""+checkClicado.value+"\"...";
				var bbox = getMapBoundingBoxAsArray();
				var req = getRequestAJAX();
				var identificador = "id";
				if ( checkClicado.getAttribute("buscarPor") == "publicidade" )
					identificador = "publicidadeId";
				else if ( checkClicado.getAttribute("buscarPor") == "recurso" )
					identificador = "recursoId";
				var url = "estabelecimentos.jsp?"+identificador+"="+checkClicado.value+"&lat0="+bbox[0]+"&lat1="+bbox[1]+"&long0="+bbox[2]+"&long1="+bbox[3];
				req.open( "GET", url, true );
				req.onreadystatechange =  function() {
					if ( req.readyState == 4 )
						if ( req.status == 200 )
							adicionaIconesNoMapa( req.responseXML, checkClicado, uf, local, region );
				}
				req.send( null );
			} else {
				carregando();
			}
		} else {
			desmarcaIconLayer( uf, local, region );
			if ( MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS == true ) {
				mostra( "alertaniveis" );
			} else {
				MOSTRAR_ZOOM_PERMITIDO_PARA_CATEGORIAS = true;
			}
			setTimeout( "esconde( \"alertaniveis\" );", 3000 );
		}
	} else { // ocultar os estabelecimentos exibidos da categoria ou publicidade "checkClicado.value"
		adicionaIconesNoMapa( null, checkClicado, uf, local, region );
	}
}

function formatDistance( distance ) {
	if ( ! distance || distance < 0 )
		return "";
	var kilometers = Math.floor( distance / 1000 );
	var meters = distance % 1000;
	if ( kilometers > 0 )
		return kilometers + "," + Math.round( meters/100 ) + " Km";
	else
		return meters + " m";
}

function formatTime( time ) {
	if ( ! time || time < 0 )
		return "";

	var restante = time;

	var horas = Math.floor( restante / 3600 );
	restante %= 3600;

	var minutos = Math.floor( restante / 60 );

	if ( horas > 0 && minutos <= 0 )
		return horas+" hora"+plural(horas);
	else if ( horas > 0 )
		return horas+" hora"+plural(horas)+", "+minutos+" minuto"+plural(minutos);
	else
		return minutos+" minuto"+plural(minutos);
}

function plural( n ) {
	return n == 1 ? "" : "s";
}

function inverterRota() {
	var end1 = jQuery("input#enderecoTracar1");
	var end2 = jQuery("input#enderecoTracar2");
	var tmp = end1.val();
	
	end1.val(end2.val());
	end2.val(tmp);
	jQuery('form#formTracar').submit();
}

function sendDetailForm(id) {
	var form = document.getElementById(id);
	var ft = form.transportmode;

	if (ft.length && ft.length > 1) {
		if (ft[0].checked == true) {
		   ft = ft[0];
		} else ft = ft[1];
	}

	parent.parent.location.href = '/mapas/jsp/default.jsp?uf='+form.uf.value+'&buscar='+form.buscar.value+'&toll='+form.toll.value+
							'&transportmode='+ft.value+'&type='+form.type.value+'&origem='+form.origem.value+
							'&uf1='+form.uf1.value+'&endereco2='+form.endereco2.value+'&endereco1='+form.endereco1.value+'&cidade1='+form.cidade1.value;
}

function toggleBarra( div, button ) {
	if (button.className == 'aberto') {
		button.className = 'fechado';
	} else button.className = 'aberto';
	
	div.toggle();
}

function cleanInputs() {
	for (i=0; i<arguments.length; i++) {
		jQuery("input#"+arguments[i]).val("");
	}
}

function printMap() {
	var u = location.href;
	var url = 'http://www.hagah.com.br/mapas/jsp/printMap.jsp'+(u.substring(u.indexOf('?'),u.length));
	window.open(url,'','location=0,status=1,scrollbars=1, width=980,height=650');
}

function printRoute() {
	var u = location.href;
	var url = 'http://www.hagah.com.br/mapas/jsp/printRoute.jsp'+(u.substring(u.indexOf('?'),u.length));
	window.open(url,'','location=0,status=1,scrollbars=1, width=825,height=650');
}
