var curCity='';

function mapFramework() {

	if (GBrowserIsCompatible()) {

   	this.map = new GMap2(document.getElementById("map"));
		this.map.addControl(new GLargeMapControl());
		this.map.addControl(new GMapTypeControl())
		this.map.enableContinuousZoom();

		var lat = lng = 0;
    if ($("#id_profile-latitude").val()) lat = $("#id_profile-latitude").val();
    if ($("#id_profile-longitude").val()) lng = $("#id_profile-longitude").val();
    if(lat==0){
        lat='39.506';
        lng='2.506';
    }

  	this.map.setCenter(new GLatLng(lat, lng), 12);
		this.marker = new GMarker(new GLatLng(lat, lng), {clickable: false, bouncy: true, draggable: true}); 
  	this.map.addOverlay(this.marker);

		GEvent.addListener(this.marker, "dragend", function(){
    	$("img.loading").show();
    	var point = this.getLatLng();
    	//alert(point.lat().toFixed(6));
      $("#id_profile-latitude").val(point.lat().toFixed(6));
      $("#id_profile-longitude").val(point.lng().toFixed(6));
    	$.getJSON("/accounts/profile/getcountry_info/" + point.lat() + "/" +  point.lng() + "/", function(data) {
      	$("#id_profile-country").val(data['profile-country']);
      	$("#id_profile-location").val(data['profile-region']);
      	$("#location_info").text(data['profile-region']);
      	$("img.loading").hide();
    	});
  	});
	}
}

mapFramework.prototype.searchLocation = function() {
//	if (!$("#id_profile-zone option:selected").text()) {return;} 
	if (curCity=='') {return;} 

//    address = 'Calvia, spain'+$("#id_profile-zone option:selected").text();
    address = 'Calvia, spain '+curCity;
	$("img.loading").show();
 	geocoder = new GClientGeocoder();

	var g = this;
 	geocoder.getLatLng(address, function(point){
 		if (point) {
 			g.map.setCenter(point,14);
 			g.marker.setLatLng(point);
      $("#id_profile-latitude").val(point.lat().toFixed(14));
      $("#id_profile-longitude").val(point.lng().toFixed(14));
 			$.getJSON("/accounts/profile/getcountry_info/" + point.lat() + "/" +  point.lng() + "/", function(data) {
 				$("#id_profile-country").val(data['profile-country']);
      	$("#id_profile-location").val(data['region']);
      	$("#location_info").text(data['region']);
 				$("img.loading").hide();
 			});
 		}
 	}); 
}

var googlemaps;

function initMap() {
	googlemaps = new mapFramework();
	googlemaps.searchLocation();
}

function initMap2() {
	googlemaps = new mapFramework();
}

$(function() {

	if ($("#id_profile-zone option:selected").val()) {
      $("div.mapinfo").show();
      $.getScript("http://maps.google.com/maps?file=api&v=2.x&key=" + $("#apikey").text() + "&async=2&callback=initMap2");
	}
});

