var temMapa = false;

function telaCheia() {
    imgPopUpWindowMapa = window.open('/legba/site/mapa/?vCod='+vCod+'&vLat='+coordsCentral.lat()+"&vLng="+coordsCentral.lng(),'mapa','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes')
}

function ajuda() {
    imgPopUpWindowAjuda = window.open('http://maps.google.com.br/support/bin/answer.py?hl=br&answer=68259','ajuda')
}

var map = null, globalRetornoXml = null, rota = null, waypoints;
var pontosDeReferecia = new Array();

// Define o ícone padrão
var iconePadraoGrande = new GIcon();
iconePadraoGrande.image = "/templates/icos/mapa/marker_sel.png";
//iconePadrao.shadow = "/templates/icos/mapa/shadow.png";
iconePadraoGrande.iconSize = new GSize(37, 45);
//iconePadrao.shadowSize = new GSize(50, 34);
iconePadraoGrande.iconAnchor = new GPoint(13, 44);
iconePadraoGrande.infoWindowAnchor = new GPoint(25, 18);
// Define o ícone padrão
var iconePadrao = new GIcon();
iconePadrao.image = "/templates/icos/mapa/marker.png";
//iconePadrao.shadow = "/templates/icos/mapa/shadow.png";
iconePadrao.iconSize = new GSize(27, 34);
//iconePadrao.shadowSize = new GSize(50, 34);
iconePadrao.iconAnchor = new GPoint(8, 33);
iconePadrao.infoWindowAnchor = new GPoint(25, 18);

// Cria o ícone padrao na geopos e adiciona o event listener
function criaMarcador(ponto, cod, textoPrevio) {
	var marcador = new GMarker(ponto, {title: textoPrevio, icon: new GIcon(iconePadrao)});
/*	GEvent.addListener(marcador, "click", function() {
		marcador.openInfoWindowHtml("<b>" + textoPrevio + "</b><br />Carregando...");
		GDownloadUrl("/ajax/detalhe.asp?vCod="+cod, function(data, responseCode) {
			marcador.openInfoWindowHtml(data);
		});
	});*/
	return marcador;
}

// Define o ícone referencia
var iconeReferencia = new GIcon();
iconeReferencia.image = "/templates/icos/mapa/marker_r.png";
//iconeReferencia.shadow = "/templates/icos/mapa/shadow_r.png";
iconeReferencia.iconSize = new GSize(19, 22);
//iconeReferencia.shadowSize = new GSize(34, 22);
iconeReferencia.iconAnchor = new GPoint(4, 21);
iconeReferencia.infoWindowAnchor = new GPoint(15, 13);

// Cria o ícone referencia na geopos e adiciona o event listener
function criaMarcadorR(ponto, titulo) {
	var marcador = new GMarker(ponto, {title: titulo, icon: new GIcon(iconeReferencia)});
	GEvent.addListener(marcador, "click", function() {
		marcador.openInfoWindowHtml("<b>" + titulo + "</b>");
	});
	return marcador;
}

function GLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mConteudo"));

		//cria o objeto directions
        gdir = new GDirections();

		//objeto q vai tratar o polyline OBS: para desenhar corretamente os poligonos no IE vc deve adicionar o namespace vml - xmlns:v="urn:schemas-microsoft-com:vml" - na tag html
        GEvent.addListener(gdir, "load", chegouDirecoes);

		//Centralizando o mapa no imóvel e renderizando o mapa
		map.setCenter(coordsCentral, 17);

		//Alvo
		var alvo = new GIcon();
		alvo.image = "/templates/icos/mapa/alvo.png";
		alvo.iconSize = new GSize(28, 28);
		alvo.iconAnchor = new GPoint(13, 13);
		map.addOverlay(new GMarker(coordsCentral, new GIcon(alvo)));
		map.addOverlay(new GMarker(coordsCentral, new GIcon(iconePadrao)));

		//Controles:
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());

		//Ícone da id5
		var iconeId5 = new GIcon();
		iconeId5.image = "/legba/site/icos/mapa/marker_id5.png";
		//iconeId5.shadow = "/templates/icos/mapa/shadow.png";
		iconeId5.iconSize = new GSize(27, 34);
		//iconeId5.shadowSize = new GSize(50, 34);
		iconeId5.iconAnchor = new GPoint(8, 33);
		iconeId5.infoWindowAnchor = new GPoint(25, 18);
		var marcadorId5 = new GMarker(new GLatLng(-9.65343, -35.70131), {title: "Conheça os responsáveis por este site", icon: new GIcon(iconeId5)});
		GEvent.addListener(marcadorId5, "click", function() {
			marcadorId5.openInfoWindowHtml("É neste local que a <b\>id5<\/b\>, empresa<br \/\>responsável pela construção deste<br \/\>site, se encontra. Estamos esperando<br \/\>por vocês para nos apresentarmos.<br \/\>Venham nos visitar!<br \/\><a href=\"http:\/\/www.id5.com.br\"\ target=\"_blank\"\>www.id5.com.br<\/a\>");
		});
		map.addOverlay(marcadorId5);

		//Carregando imóveis
		
		GDownloadUrl("/legba/site/ajax/imoveis.asp?sid="+Math.random()+"&i="+vCod, function(data, responseCode) {
			globalRetornoXml = GXml.parse(data);
			pausaImoveis(0);
		});

		mgr = new GMarkerManager(map);
	} 
}

function pausaImoveis(indice) {
	var imoveis = globalRetornoXml.documentElement.getElementsByTagName("imovel");
	if(imoveis.length > 0){
		vCodRef = imoveis[indice].getAttribute("codRef")
		if (indice < imoveis.length) {
			var ponto = new GLatLng(parseFloat(imoveis[indice].getAttribute("lat")), parseFloat(imoveis[indice].getAttribute("lng")));
			mgr.addMarker(criaMarcador(ponto, imoveis[indice].getAttribute("cod"), imoveis[indice].getAttribute("tipo")),3);
		}
	}else{
		indice = 1;
		vCodRef = vCod;
	}
	if (indice < imoveis.length-1) {
		setTimeout("pausaImoveis("+(indice+1)+")", 0)
	} else {
		//Carregando pontos de referencia
		GDownloadUrl("/legba/site/ajax/referencias.asp?sid="+Math.random()+"&vCod="+vCodRef+"&d="+distanciaPRef, function(data, responseCode) {
			globalRetornoXml = GXml.parse(data);
			pausaReferencias(0);
		});
	}
}

function pausaReferencias(indice) {
	var referencias = globalRetornoXml.documentElement.getElementsByTagName("referencia");
	if (indice < referencias.length) {
		var ponto = new GLatLng(parseFloat(referencias[indice].getAttribute("lat")), parseFloat(referencias[indice].getAttribute("lng")));
		pontosDeReferecia[referencias[indice].getAttribute("cod")] = ponto;
		mgr.addMarker(criaMarcadorR(ponto, referencias[indice].getAttribute("titulo")),3);
	}
	if (indice < referencias.length-1) {
		setTimeout("pausaReferencias("+(indice+1)+")", 0)
	}
}

function vaiMapa(cod) {
	if (GBrowserIsCompatible()) {
		if (typeof(pontosDeReferecia.length)!="undefined") { //Verifica se a array está pronta
			if (pontosDeReferecia[cod] != undefined) { //Verfica se o valor existe
				map.panTo(pontosDeReferecia[cod]);
			}
		}
	}
}

function mapaDirecoes(cod) {
	if (GBrowserIsCompatible()) {
		if (typeof(pontosDeReferecia.length)!="undefined") { //Verifica se a array está pronta
			if (pontosDeReferecia[cod] != undefined) { //Verfica se o valor existe
				if (rota != null) {
					map.removeOverlay(rota);
				}
				waypoints = new Array(coordsCentral, pontosDeReferecia[cod]);
				map.openInfoWindow(pontosDeReferecia[cod], "Carregando rota...");
				gdir.loadFromWaypoints(waypoints,{ "getPolyline":true });
			}
		}
	}
}

function chegouDirecoes() {
	for (var i = 0; i <= gdir.getNumRoutes(); i++) {
		rota = gdir.getPolyline();
		var ponto = gdir.getMarker(i).getPoint();
		map.closeInfoWindow();
		map.addOverlay(rota);
		map.openInfoWindow(ponto, Math.round(rota.getLength()) + " metros do im&oacute;vel at&eacute; aqui.");
	}
}

function centroMapa() {
	if (GBrowserIsCompatible()) {
		map.panTo(coordsCentral);
	}
}

function adicionaEventos() {
	redimensionaMapa();
	if (window.attachEvent) {
		window.attachEvent("onresize", function() {redimensionaMapa()});
	} else {
		window.addEventListener("resize", function() {redimensionaMapa()}, false);
	}
}

function redimensionaMapa() {
	var divMapa = document.getElementById("mConteudo");
	if (divMapa==null) return;
	var largura = 0, altura = 0;
	if(typeof(window.innerWidth) == "number") {
		//Non-IE
		largura = window.innerWidth;
		altura = window.innerHeight;
	} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		largura = document.documentElement.clientWidth;
		altura = document.documentElement.clientHeight;
	} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		largura = document.body.clientWidth;
		altura = document.body.clientHeight;
	}
	if (altura >= 0 && largura >= 0) {
		divMapa.style.width = largura + "px";
		divMapa.style.height = altura + "px";
		map.checkResize();
		map.setCenter(coordsCentral, 17);
	}
}
