
var map = null ; 
var icon_ep = null;
var gdir;

// wheel Mouse controls
var wheelMousing = false ;
var idWheelTimeout = 0 ;
  
    
function loadMap(divName, withOverview, lat, long) {
  if (GBrowserIsCompatible()) {
    
    icon_ep = new GIcon() ;
    icon_ep.image = req_base+"img/maps/pinh.png";  
    icon_ep.shadow = req_base+"img/maps/shadow.png";
    icon_ep.iconSize = new GSize(45, 45);
	icon_ep.shadowSize = new GSize(67, 45);
	icon_ep.iconAnchor = new GPoint(22, 45);
	icon_ep.infoWindowAnchor = new GPoint(5, 1);
	
	icon_h1 = new GIcon() ;
    icon_h1.image = req_base+"img/maps/pinh1.png";  
    icon_h1.shadow = req_base+"img/maps/shadow.png";
    icon_h1.iconSize = new GSize(45, 45);
	icon_h1.shadowSize = new GSize(67, 45);
	icon_h1.iconAnchor = new GPoint(22, 45);
	icon_h1.infoWindowAnchor = new GPoint(5, 1);
	
	icon_h2 = new GIcon() ;
    icon_h2.image = req_base+"img/maps/pinh2.png";  
    icon_h2.shadow = req_base+"img/maps/shadow.png";
    icon_h2.iconSize = new GSize(45, 45);
	icon_h2.shadowSize = new GSize(67, 45);
	icon_h2.iconAnchor = new GPoint(22, 45);
	icon_h2.infoWindowAnchor = new GPoint(5, 1);
	
	icon_h3 = new GIcon() ;
    icon_h3.image = req_base+"img/maps/pinh3.png";  
    icon_h3.shadow = req_base+"img/maps/shadow.png";
    icon_h3.iconSize = new GSize(45, 45);
	icon_h3.shadowSize = new GSize(67, 45);
	icon_h3.iconAnchor = new GPoint(22, 45);
	icon_h3.infoWindowAnchor = new GPoint(5, 1);

	icon_h4 = new GIcon() ;
    icon_h4.image = req_base+"img/maps/pinh4.png";  
    icon_h4.shadow = req_base+"img/maps/shadow.png";
    icon_h4.iconSize = new GSize(45, 45);
	icon_h4.shadowSize = new GSize(67, 45);
	icon_h4.iconAnchor = new GPoint(22, 45);
	icon_h4.infoWindowAnchor = new GPoint(5, 1);
	
	icon_h5 = new GIcon() ;
    icon_h5.image = req_base+"img/maps/pinh5.png";  
    icon_h5.shadow = req_base+"img/maps/shadow.png";
    icon_h5.iconSize = new GSize(45, 45);
	icon_h5.shadowSize = new GSize(67, 45);
	icon_h5.iconAnchor = new GPoint(22, 45);
	icon_h5.infoWindowAnchor = new GPoint(5, 1);
	
    map = new GMap2(document.getElementById(divName));	    
    map.enableDoubleClickZoom() ;
    
    /*
    G_NORMAL_MAP.getName = function() { return 'Mapa'; }
    map.addMapType(G_NORMAL_MAP);
    G_HYBRID_MAP.getName = function() { return 'Híbrido'; }
    map.addMapType(G_HYBRID_MAP);
    G_SATELLITE_MAP.getName = function() { return 'Satélite'; }
    map.addMapType(G_SATELLITE_MAP);
    */
    
    map.setCenter(new GLatLng(42.11794, -3.902393), 4);
    
    map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());
    var Tsize = new GSize(156, 156); 
    
    if (withOverview) {
	    overview = new GOverviewMapControl(Tsize); 
	   /* var cc = map.fromLatLngToDivPixel(map.getCenter());
	 	var left = cc.x - 60;
	 	var right = cc.y - 40; 
	    var pos = new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(left, right));
	    map.addControl(overview,pos);   */
	    map.addControl(overview);
	}
	
	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "error", handleErrors);
	    
    // ZoomEnd event
    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel ) {
        if (!wheelMousing) {
            //alert ("ZOOMEND");
        }
    });
    
    // MoveEnd event
    GEvent.addListener(map, "moveend", function() {
        if (!wheelMousing) 
        {
        	//alert ("MOVEEND");    
        }
	});
 
  }
}

function setLocation(longitude, latitude, zoom) {
	center = new GLatLng(latitude, longitude);
	map.setCenter(center, zoom);

	
    var marker = new GMarker(center, {draggable: true, icon: icon_ep});

    GEvent.addListener(marker, "dragstart", function() {
    	//map.closeInfoWindow();
    });

    GEvent.addListener(marker, "dragend", function() {
    	var latlong = marker.getLatLng();
    	//marker.openInfoWindowHtml("Nueva posición: " + latlong.lat() + ", " + latlong.lng());
    	$("#latitude").val(latlong.lat()); 
    	$("#longitude").val(latlong.lng());
    });

    map.addOverlay(marker);
}

function setItem(longitude, latitude, zoom) {
	center = new GLatLng(latitude, longitude);
	map.setCenter(center, zoom);

    var marker = new GMarker(center, {icon: icon_ep});

    map.addOverlay(marker);
}

function addItem(longitude, latitude, stars, zoom, myHtml) {
	center = new GLatLng(latitude, longitude);
	map.setCenter(center, zoom);
	if (stars == '1') {
		var marker = new GMarker(center, {icon: icon_h1});
	}
	else if (stars == '2') {
		var marker = new GMarker(center, {icon: icon_h2});
	}
	else if (stars == '3') {
		var marker = new GMarker(center, {icon: icon_h3});
	}
	else if (stars == '4') {
		var marker = new GMarker(center, {icon: icon_h4});
	}
	else if (stars == '5') {
		var marker = new GMarker(center, {icon: icon_h5});
	}
	else {
		var marker = new GMarker(center, {icon: icon_ep});
	}
	
	GEvent.addListener(marker, "click", function() {
		map.openInfoWindowHtml(new GLatLng(latitude, longitude), myHtml);
	});
	

    map.addOverlay(marker);
}

function allowResizeMap()
{
/*
 $("#map").resizable({
 
 	autohide: true,
 	minHeight: 186,
    start : function(){
      $("#resB").show();
      },
     stop : function(){
      map.checkResize();
      } 
     });
     */
}

function addControlsAnimation(){
	
	$("#resB").hide();
    $("#expB").click(function(){
      $("#map").animate({ 
       height: "400px"
      }, "normal","swing",function(){map.checkResize();});
      $("#resB").show();
      
    });
     $("#resB").click(function(){
      $("#map").animate({ 
       height: "200px"
      }, "normal","swing",function(){map.checkResize();});
       $("#resB").hide();
    });
    
    
    $("#minB")
    .click(function(){
   		 $("#map_frame").slideUp("normal",
   		  function(){
   			 $("#map_hidden_frame").slideDown();
    			}
    	);
   	})
     $("#expB2")
    .click(function(){
   		 $("#map_hidden_frame").slideUp("normal",
   		  function(){
   			 $("#map_frame").slideDown();
    			}
    	);
   	})

}


function locateIt(req_base, message_notlocated, street, cp, country, province, location) {
	map.clearOverlays();
	
	
	
	var geocoder = new GClientGeocoder();
	var zoom = 17;
	var search_string = "";

	if (street == "") {
		zoom = 14;	
	}
	else {
		search_string += street + ", ";
	}
	if (location == "") {
		zoom = 7;
	}
	else {
		search_string += location + ", ";
	}
	if (province == "") {
		zoom = 4;
	}
	else {
		search_string += province + ", ";
	}
	if (country == "") {
		zoom = 4;
		country = "Spain";
	}
	else {
		search_string += country;
	}
	
	//geocoder.setViewport(spain_bounds);
	geocoder.setBaseCountryCode('.es');
	geocoder.getLatLng(
	    search_string,
	    function(point) {
	      if (!point) {
	        alert(message_notlocated);
	      } else {
	      	$("#latitude").val(point.lat()); 
        	$("#longitude").val(point.lng());
	      	setLocation(point.lng(), point.lat(), zoom);
	      }
	    }
	);

	
	
	/*$.post(req_base+'?do=GetLatLong', {
	    street: street,
	    cp: cp,
	    province: province,
	    location: location,
	    country: country
	}, function(cad) {
		var data = cad.split(",");
		var latitude = data[0];
		var longitude = data[1];
		var zoom = parseInt(data[2]);
		var error = data[3];
		
		$("#latitude").val(latitude); 
        $("#longitude").val(longitude);
        
        setLocation(longitude, latitude, zoom);
	    
	    if (error) {
	    	alert(message_notlocated);
	    }
	    
	});*/
}
	
function init(divName, withOverview)
{
    loadMap(divName, withOverview);    
    allowResizeMap();
    addControlsAnimation();
}

function setDirections(fromAddress, lat, long, lang) {
  gdir.load("from: " + fromAddress + " to: @" + long + ", " + lat,
            { "locale": lang });
}

//Manejo de errores
function handleErrors(){
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
     alert("No se puede calcular la ruta desde la dirección indicada, compruebe que está bien escrita o esta no sa ambigua");
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
     alert("Error desconocido");

   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
     alert("No se ha introducido una dirección de inicio");

   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
     alert("Clave usada por el mapa no valida o no corresponde con el dominio desde el que se usa.");

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
     alert("La dirección no puede ser parseada.");

   else alert("oppps ha ocurrido un error :(.");

}

function onGDirectionsLoad(){ 
}
