var locale	  = "pt_BR";
var count	  = 0;
var list	  = 0;

var map;
var route;
var gdir;
var endereco;

var toAddressLatitude;
var toAddressLongitude;

var tipoMapa = "mapa";

var url = "http://www.bradescoautocenter.com.br";

function traceRoute(fromAddress, toAddress) {
	//Verifica se foi digitado o endereço de partida.
	if (fromAddress=='') {
		alert('Favor informar o endereço de partida.');
		document.forms[0].de.focus();
	
	//Verifica se o browser é compatível.
	}else if (!GBrowserIsCompatible()) {	
		alert('Browser incompatível');
	
	//Verifica se chama direto a rota.
	}else if (count>0) {
		document.getElementById("directions").innerHTML = "";
		document.getElementById("distance").innerHTML = "";
		setDirections(unescape(fromAddress), unescape(toAddress), locale);
	
	//Verifica se chama a funcionalidade para criar a rota.
	}else {
		document.getElementById("directions").innerHTML = "";
		document.getElementById("distance").innerHTML = "";
		route = new GMap2(document.getElementById("map"));
		route.addControl(new GSmallMapControl());
		gdir = new GDirections(route, document.getElementById("directions"));
		GEvent.addListener(gdir, "error", handleErrors);
		setDirections(unescape(fromAddress), unescape(toAddress), locale);
		count=1;
		tipoMapa="rota";
	 }	
 }		
 
 function setDirections(fromAddress, toAddress, locale) {
 	document.getElementById("distance").innerHTML = "<strong>Rota de carro para "+endereco+"</strong>"
	gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
 }

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	  alert("O endereço de origem não foi encontrado. Favor refinar os dados de origem.");
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	  alert("A geocodificação ou a direção obtida não foi processada corretamente.\n Código do erro: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	  alert("Nenhuma consulta foi especificada.\n Código do erro: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	  alert("Chave inválida. \n Código do erro: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	  alert("Rota não analisada com êxito.\n Código do erro: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS)  
	  alert("Não há rota disponível entre os dois pontos ou não há dados de rota da região.\n Código do erro: " + gdir.getStatus().code);
	else alert("Ocorreu um erro desconhecido." + gdir.getStatus().code);
}

function createMarker(point, address) { 
	var marker = new GMarker(point, getIcon()); 
	GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(address); } ); 
	return marker; 
} 

function showMap(latitude, longitude, toAddress) {
	if (GBrowserIsCompatible()) {
		toAddressLatitude = latitude;
		toAddressLongitude = longitude;
		
		map  = new GMap(document.getElementById("map"));
		var point = new GPoint(latitude, longitude); 
		endereco = toAddress;
		var marker = createMarker(point, endereco); 
	
		//Add controles da interface do Mapa.
		map.addControl(new GSmallMapControl());

		//Localização do BAC.
		map.addOverlay(marker); 
		map.centerAndZoom(point, 1); 
		map.checkResize();
	}else {
		alert('Browser incompatível com o serviço.');
	}	
}

function getIcon() {
	var icone = new GIcon(G_DEFAULT_ICON);
	
	icone.transparent = url+"/img/icone_bradesco.png";
	icone.image = url+"/img/icone_bradesco.png";
	icone.printImage = url+"/img/icone_bradesco.png";
	icone.iconSize = new GSize(59, 44);
	
	return icone;
}

function printMap(mapa, latitude, longitude, fromAddress, toAddress){
	if (mapa=="rota") {
		endereco=toAddress;
		traceRoute(fromAddress, longitude+','+latitude);
	}else {
		showMap(latitude, longitude, fromAddress);
		document.getElementById("painel_esquerda").style.display = 'none';
	}	
	setTimeout("window.print()", 5000);
}

function openMapPage(latitude, longitude, address, titulo) {
	var titulo = document.getElementById('titulo'+titulo).innerHTML;
	window.open(url+'/internas/onde_encontrar_mapa.asp?x='+latitude+'&y='+longitude+'&endereco='+address+'&titulo='+titulo,'Mapa');
}			

function searchList(fromAddress, toAddress){
	//Verifica se foi digitado o endereço de partida.
	if (fromAddress=='') {
		alert('Favor informar o endereço de partida.');
		document.forms[0].de.focus();
	
	//Verifica se o browser é compatível.
	}else if (!GBrowserIsCompatible()) {	
		alert('Browser incompatível');
	
	//Verifica se chama a funcionalidade para exibir a lista.
	}else {
		var coordenada = new GLatLngBounds(new GLatLng(-23,-46), new GLatLng(-23,-46))
		var geocoder = new GClientGeocoder();
		var address = document.getElementById("fromAddress").value;

		geocoder.setViewport(coordenada);
		geocoder.getLocations(address, searchCallback);
	}	
}

function searchCallback(locations){
	var html = [];
	
	if (locations.Status.code!=200) {
		alert("O endereço de origem não foi encontrado. Favor refinar os dados de origem.");
	}else {
		if (locations.Placemark.length > 1) {
			html.push("<span class='vermelho'>Você quis dizer:</span>");
			for(var i=1; i<locations.Placemark.length; i++){
				html.push("<a href=javascript:preparedTraceRoute('"+escape(locations.Placemark[i].address)+"');>"+locations.Placemark[i].address+"</a>");
			}
			document.getElementById("directions").innerHTML = html.join("<br />");
		}else{
			preparedTraceRoute(escape(locations.Placemark[0].address));
		}	
	}	
}

function preparedTraceRoute(fromAddress) {
	var toAddress = toAddressLongitude + "," + toAddressLatitude;
	document.getElementById("fromAddress").value = unescape(fromAddress);
	traceRoute(document.getElementById("fromAddress").value, unescape(toAddress));
}

function getLabel(line){
	if (line<9) {
		label = (line+1) + '. ';
	}else {
		label = (line+1) + '.';
	}

	list = (line+1);

	return label;
}

function adjustScreen() {
	var mapa = document.getElementById("map");
	//Largura do mapa menos a largura da coluna esquerda
	mapa.style.width = document.body.offsetWidth-340; 
	
	//Altura do topo menos a altura do topo
	mapa.style.height = document.body.offsetHeight-170; 
	
	var rota = document.getElementById("rota");
	//Altura do topo menos a altura do topo
	rota.style.height = mapa.style.height;
}	

function openMapPrint(latitude, longitude, fromAddress, toAddress) {
	oJan = window.open(url + '/internas/onde_encontrar_mapa_imprimir.asp?mapa='+tipoMapa+'&latitude='+latitude+'&longitude='+longitude+'&fromAddress='+fromAddress+'&toAddress='+toAddress, '', 'left=0,top=0,toolbar=0,location=0,status=0,menubar=0,resizible=0, scrollbars=1, width=780,height=550');
}