var UsrMap = {
	map:null,
	baseurl:"http://w5.fotonatura.org/kml/usermap.kml",
	geoXml:null,
	icon:null,
	mgr:null,
	url:null,
	_idgal:$("#idgaleria"),
	id:0,
	maptainer:$("#usrmap").get(0),
	mgrOptions:{ borderPadding: 50, maxZoom: 18, trackMarkers: true },
	
	// methods
	init:function () {
		if (GBrowserIsCompatible()) {
				// iconos
				UsrMap.icon = new GIcon();
				UsrMap.icon.image = "/img/marker.png";
				UsrMap.icon.iconSize = new GSize(21, 31);
				
				UsrMap.icon.iconAnchor = new GPoint(7, 29);
				UsrMap.icon.infoWindowAnchor = new GPoint(10, 10);
				
				// crea un  mapa
				UsrMap.map = new GMap2(UsrMap.maptainer);
				
				UsrMap.mgr = new GMarkerManager(UsrMap.map, UsrMap.mgrOptions);
				
				//map.setMapType(G_HYBRID_MAP);
				UsrMap.map.addControl(new GLargeMapControl());
				UsrMap.map.addControl(new GMapTypeControl());
				UsrMap.map.addControl(new GScaleControl());
				UsrMap.map.addControl(new GOverviewMapControl());
				UsrMap.map.enableScrollWheelZoom();
				UsrMap.map.setCenter(new GLatLng(10, 10), 2);
				// esto debe ir despues del setCenter
				UsrMap.map.setMapType(G_NORMAL_MAP);
				// calcula los puntos extremos y el zoom
				var mbr = UsrMap.getMBR();	
				// puntos minimos y maximos
				UsrMap.map.setZoom(UsrMap.map.getBoundsZoomLevel(mbr));
				UsrMap.map.panTo(mbr.getCenter());
				UsrMap.map.enableDoubleClickZoom();

				// obtiene lista de puntos
				if (UsrMap._idgal.val() != 0) {
					UsrMap.id = UsrMap._idgal.val();
				}
				$.ajax({
					url: "/ajax/getuserpoints.php",
					data: "id="+UsrMap.id,
					dataType: "json",
					success: UsrMap.show_localities
				});
				
		}
	},
	show_localities:function (json) {
		var list = json.images,
		list_size = 0,
		markerlist = [],
		marker,
		point;
		
		if (list != undefined) {
			list_size =  list.length;
			for (var i=0; i<list_size; i++) {
				if (list[i].lat != null && list[i].lng != null) {
					point = new GLatLng(list[i].lat, list[i].lng);
					marker = UsrMap.create_marker(point, list[i].title, list[i].src, list[i].link);
					markerlist.push(marker);
				}
			}
			UsrMap.mgr.addMarkers(markerlist, 0);
			UsrMap.mgr.refresh();
		}
	},
	create_marker:function(point, titulo, image, link) {
// 		var marker = new GMarker(point, icon);
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml("<div class=\"infow\"><p>"+titulo+"</p><a href=\""+link+"\"><img src=\""+image+"\" title=\"Ver imagen\" /></a></div>");
		});
		
		return marker;
	},
	getMBR:function () {
		// coordenadas extremas
		var swlat = $("#swlat").val();
		var swlng =  $("#swlng").val();
		var nelat =  $("#nelat").val();
		var nelng =  $("#nelng").val();
		
		var sw = new GLatLng(swlat, swlng);
		var ne = new GLatLng(nelat, nelng);
		
		var mbr = new GLatLngBounds(sw,  ne)
		return mbr;
	}
}
