var map = null;
var geocoder = null;
var gdir;
var addressMarker;
var city;
var state;
var city_to;
var state_to;
var city_from = getCookie('city_from');
var state_from = getCookie('state_from');

var gicon = [];
gicon["red_pushpin"] = new GIcon(G_DEFAULT_ICON, "images/map_icons/dot_red_pushpin.png");
gicon["red_ball"]    = new GIcon(G_DEFAULT_ICON, "images/map_icons/dot_red_ball.png");
gicon["caracoles"]   = new GIcon(G_DEFAULT_ICON, "images/map_icons/dot_caracoles.png");

function route(type){
  var address = getCookie('address_from');
  if(!address)
    address = "Rua Caracoles, 53";
  
  document.getElementById('route').style.display = "block";
  document.getElementById('textroute').style.display = "none";
  if (type == 2) {
	  document.getElementById('routeTo').style.display = "none";
	  document.getElementById('to').style.display = "block";
  }
  
  document.getElementById('from').value = address;
}

function showTooltip(marker,tooltip) {
  tooltip.innerHTML = marker.tooltip;
  var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
  var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  var anchor = marker.getIcon().iconAnchor;
  var width = marker.getIcon().iconSize.width;
  var height = tooltip.clientHeight;
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x - width, offset.y - point.y - anchor.y + height)); 
  pos.apply(tooltip);
  tooltip.style.visibility = "visible";
}

function clearTooltip(tooltip) {
  map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
  tooltip.style.visibility = "hidden";
}

function showAddress(address, name, link, center, type, balloon) {
  var icon_name;
  var marker;
	hideRota();
	if (geocoder) {
	  geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	      } else {
	        if(!city_from)
					  city_from = city;
					if(!state_from)
					  state_from = state;
          switch(type) {
            case 0:
              //map.setCenter(point, 15);
              icon_name = "caracoles";
              break;

            case 1:
              icon_name = "red_pushpin";
              break;

            case 2:
              icon_name = "red_ball";
              break;

            default:
              icon_name = "red_pushpin";
          }
          if (center)
            map.setCenter(point, center);
          marker = new GMarker(point,gicon[icon_name]);
	        map.addOverlay(marker);

          if (type != 0 || balloon == 0 || balloon == 1 || balloon == 3) {
            var tooltip = document.createElement("div");
            clearTooltip(tooltip);
            marker.tooltip = '<div class="tooltip"><b>'+name+'</b><\/div>';
            //marker.tooltip = balloon ? '<div class="tooltip"><b>'+name+'</b><\/div>' : '<div class="tooltip"><img src="'+name+'"><\/div>';
            GEvent.addListener(marker,"mouseover", function() {
              showTooltip(marker,tooltip);
            });        
            GEvent.addListener(marker,"mouseout", function() {
              tooltip.style.visibility = "hidden"
            });
            GEvent.addListener(marker, "click", function() {
              window.location = link;
            });
          }

          if (balloon == 2 || balloon == 3) {
  	        var message = '';
	          if (name) {
	            message = message.concat('<div style="width:300px;">');
              message = message.concat('<b>',name,'</b>');
              message = message.concat('<br><br>');
              message = message.concat('</div>');
  	          message = message.concat('<div style="width:300px; height:40px; bottom:0px">');
  	          message = message.concat('<form method="post" action="" id="formDirection" onsubmit="setCookie(\'address_from\',this.from.value); setCookie(\'city_from\',this.city_from.value); setCookie(\'state_from\',this.state_from.value); showTrace(); setDirections(this.from.value + \', \' + this.city_from.value + \', \' + this.state_from.value,this.to.value); return false;">');
	            message = message.concat('<table id="route" style="display: none">');
	            message = message.concat('<tr><td colspan = 2>');
	            message = message.concat('<input name="to" type="text" id="to" value="',address,'" size="66" class="input" style="display: none" />');
	            message = message.concat('<input name="from" type="text" id="from" class="inputheader" size="66" />');
	            message = message.concat('</td></tr>');
	            message = message.concat('<tr><td align = "left">');
	            message = message.concat('<input name="city_from" type="text" id="city_from" class="inputheader" value="',city_from,'" size="8" class="input"/>');
	            message = message.concat('<input name="state_from" type="text" id="state_from" class="inputheader" value="',state_from,'" size="1" class="input"/>');
              message = message.concat('</td>');
	            message = message.concat('<td align = "right">');
	            message = message.concat('<input type="submit" name="button3" id="butto32" value="Traçar Rota" class="button"/>');
	            message = message.concat('</td></tr></table><br />');
	            message = message.concat('</form>');
	            message = message.concat('<a id="textroute" href="javascript:route(1);">Traçar Rota</a>');
	            message = message.concat('</div>');
	          } else {
	            array_address = address.split(', ');
	            message = message.concat('<div id="routeTo" style="width:300px;">');
              message = message.concat('<b>',address,'</b>');
              message = message.concat('<br><br>');
              message = message.concat('</div>');
              message = message.concat('<div style="width:300px; height:95px; bottom:0px">');
              message = message.concat('<form method="post" action="" id="formDirection" onsubmit="setCookie(\'address_from\',this.from.value); setCookie(\'city_from\',this.city_from.value); setCookie(\'state_from\',this.state_from.value); showTrace(); setDirections(this.from.value + \', \' + this.city_from.value + \', \' + this.state_from.value,this.to.value + \', \' + this.city_to.value + \', \' + this.state_to.value); return false;">');
              message = message.concat('<table id="route" style="display: none">');
              message = message.concat('<tr><td colspan = 2>');
              message = message.concat('Origem:<br>');
              message = message.concat('<input name="from" type="text" id="from" class="inputheader" size="66" />');
              message = message.concat('</td></tr>');
              message = message.concat('<tr><td align = "left">');
              message = message.concat('<input name="city_from" type="text" id="city_from" class="inputheader" value="',city_from,'" size="8"/>');
              message = message.concat('<input name="state_from" type="text" id="state_from" class="inputheader" value="',state_from,'" size="1"/>');
              message = message.concat('<br></td>');
              message = message.concat('<tr><td colspan = 2>');
              message = message.concat('Destino:<br>');
              message = message.concat('<input name="to" type="text" id="to" value="',array_address[0] + ", " + array_address[1],'" size="66" class="inputheader" style="display: none" />');
              message = message.concat('</td></tr>');
              message = message.concat('<tr><td align = "left">');
              message = message.concat('<input name="city_to" type="text" id="city_to" class="inputheader" value="',city,'" size="8"/>');
              message = message.concat('<input name="state_to" type="text" id="state_to" class="inputheader" value="',state,'" size="1"/>');
              message = message.concat('</td>');
              message = message.concat('<td align = "right">');
              message = message.concat('<input type="submit" name="button3" id="butto32" value="Traçar Rota" class="button"/>');
              message = message.concat('</td></tr></table><br><br>');
              message = message.concat('</form>');
              message = message.concat('<br><br><a id="textroute" href="javascript:route(2);">Traçar Rota</a>');
              message = message.concat('</div>');
	          }
	          GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(message);});
            if (type == 0)
	            marker.openInfoWindowHtml(message);
          }
	      }
	    }
	  );
	}
}

function showRota() {
	var strbusca = document.getElementById('address').value;
	var div = document.getElementById('direction');
	var origem = document.getElementById('from');
	div.style.display = 'block';
	
	origem.value = strbusca;
}

function showTrace() {
	var mapa = document.getElementById('mapGoogle');
	var trace = document.getElementById('trace');

	//mapa.style.width = '570px';
  mapa.style.top = '-500px';
  //mapa.style.left = '220px';
	
	trace.style.display = 'block';
	
  trace.style.top = '510px';
	trace.style.width = '795px';
}
    
function hideTrace() {
	var trace = document.getElementById('trace');
	var mapa = document.getElementById('mapGoogle');

  //AQUI OTA	
  //mapa.style.width = '800px';
	
  mapa.style.top = '0';
	mapa.style.left = '0';
	trace.style.display = 'none';
}

function hideRota() {                                                                                                                                           
  var div = document.getElementById('direction');                                                                                                               
  div.style.display = 'none';                                                                                                                                   
  hideTrace();                                                                                                                                                  
}

function setDirections(fromAddress, toAddress) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": "pt_BR" });
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		//alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
		alert("Endereço especificado não foi encontrado.");
	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
  	alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
  	alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
		//else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
		//alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
  	alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
  	alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	} else {
  	alert("An unknown error occurred.");
	} 
}

function onGDirectionsLoad(){ 
	// Use this function to access information about the latest load()
	// results.
	// e.g.
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
}


