var map;
var address;
var map;
var gdir;
var geocoder = null;
var addressMarker;

function initialize() {
	map = new GMap2(document.getElementById("map_canvas"));
	gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
	
	// GEO CODER FOR SEARCH
	geocoder = new GClientGeocoder();
	
	point = new GLatLng(lat,lng);
	// sinaliza a localizacao
	map.setCenter(point, zoom);
	map.enableScrollWheelZoom(true);
	//wikipedia
	var myLayer = new GLayer("org.wikipedia.pt");
        //map.addOverlay(myLayer);
	
	
	//controls
	//map.setUIToDefault();
	
	// marcadores personalizados
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = thumb;
	icon.shadow = "http://tweetiesms.com/imgs/bg_maps_profile.png";
	icon.iconSize = new GSize(35, 35);
	icon.shadowSize = new GSize(39, 38);
	icon.infoWindowAnchor = new GPoint(16,0);
	
	// Set up our GMarkerOptions object
	markerOptions = { icon: icon, draggable: false };
	var marker = new GMarker(point, markerOptions);
	
	/*GEvent.addListener(marker, "dragstart", function() {
		map.closeInfoWindow();
	});
	
	GEvent.addListener(marker, "dragend", function() {
	      marker.openInfoWindowHtml(titBox);
	});*/
	
	if (showB == "true"){
		GEvent.addListener(marker,"click", function() {
			marker.openInfoWindowHtml(titBox);
		});
		
		marker.openInfoWindowHtml(titBox);
	}
	
	// add maker
	map.addOverlay(marker);
}
function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}
function setDirections(toAddress) {
		var toAddressText = document.getElementById('toAddress');
		toAddressText.value = toAddress;
	if(toAddress != ''){
		gdir.load(
				"from: " +
				adressFrom +
				" to: " + toAddress.replace(/^\s+|\s+$/g,""),
				{ "locale": 'pt' }
			  );
	}
}
 
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);
       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(){ 
	map.closeInfoWindow();
	//alert(gdir.getStatus());
}

function addAddressToMap(response) {
	map.clearOverlays();
	if (!response || response.Status.code != 200) {
	  alert("Sorry, we were unable to geocode that address");
	} else {
	  place = response.Placemark[0];
	  point = new GLatLng(place.Point.coordinates[1],
			      place.Point.coordinates[0]);
	  //controls
	//map.setUIToDefault();
	
	// marcadores personalizados
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.image = thumb;
	icon.shadow = "http://tweetiesms.com/imgs/bg_maps_profile.png";
	icon.iconSize = new GSize(35, 35);
	icon.shadowSize = new GSize(39, 38);
	icon.infoWindowAnchor = new GPoint(16,0);
	
	// Set up our GMarkerOptions object
	markerOptions = { icon: icon, draggable: false };
	var marker = new GMarker(point, markerOptions);
	
	  map.addOverlay(marker);
	  
	  var 	titBox2	= "<div class='infoBox'>";
		titBox2	+= "<div class='contentBox'>";
		titBox2	+= divBG;
		titBox2	+= "@<a href='http://twitter.com/"+user_name+" ' target='_blank'>"+user_name+"</a>";		
		titBox2	+= "<div style='float: left; width: 230px;'>";	
		titBox2	+= placeT;	
		titBox2	+= '<br>' + placeD;
		titBox2	+= "</div>";	
		titBox2	+= "<div style='float: left; width: 300px'>";
		titBox2	+= '<br>'	
		titBox2	+= place.address.split(',')[0] + ' - ';	
		titBox2	+= place.address.split(',')[1];
		titBox2	+= '<br>'	
		titBox2	+= '<br>'	
		titBox2	+= "</div>";;
		titBox2	+= "<div class='details'>";
		titBox2	+= "<br><a href='javascript:void'>Veja no Twitter</a> - <a href='javascript:void'>@Reply</a><br>";
		titBox2	+= "<span style='font-size: 11px; color: #ccc'>";
		titBox2	+= "Lat: "+place.Point.coordinates[1]+" - Long: "+place.Point.coordinates[0];
		titBox2	+= "</span>";	
		titBox2	+= "</div>";
		titBox2	+= "</div>";	
		titBox2	+= "</div>";
		marker.openInfoWindowHtml(titBox2);
	}
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(placeTitle, placeDesc, placeAddress) {
	placeAddress = placeAddress.replace(/^\s+|\s+$/g,"");
	placeT = placeTitle;
	placeD = placeDesc;
	geocoder.getLocations(placeAddress, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(placeAddress) {
	showLocation();
}
