var map = null;
var mapEvents = function () {
	var site_id = document.getElementById("site_id");
	var default_type = document.getElementById("default_map_type").value;

	// map = Map.init(20, 0, 2, default_type, Map.getMBR());
	map = Map.init(20, 0, 2, default_type);
	getLocations(site_id.value);
}

var getLocations = function(site_id) {
	var ajax = new Ajax.Request('/ajax/getgeotaggedimgs.php?siteid='+site_id, {method: 'get', onComplete: showLocations});
}

var showLocations = function(response) {
	var json = eval(response.responseText);
	var imglist = json.images;
	// site info
	var site_name = json.site_name;
	var hosting_type = json.hosting_type;
	var domain = json.domain;
	var img_dir = json.img_dir;
	var gallery_id = json.gallery_id;
	
	if (hosting_type == 'domain') {
		var base_url = "/images/";
	} else {
		var base_url = "/"+site_name+"/images/";
	}
	
	for (var i=0; i<imglist.length; i++) {
		var point = new GLatLng(imglist[i].lat, imglist[i].lng);
		var title = imglist[i].title;
		var image = "http://"+domain+img_dir+imglist[i].thumb;
		var link = base_url+imglist[i].id+"/"+gallery_id+"/";
		var desc = imglist[i].desc;
		var marker = createMarker(point, title, desc, image, link);

		map.addOverlay(marker);
	}
}

function createMarker(point, titulo, desc, image, link) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("<div class=\"infow\"><h4>"+titulo+"</h4><a href=\""+link+"\"><img src=\""+image+"\" title=\"Ver imagen\" /></a></div></div>");
  });
  return marker;
}

var Map={
	mgr:null,
	dragmarker:null,
	defaultzoom:1,
	defaultType:'G_PHYSICAL_MAP',
	clean:function() {
		map.clearOverlays();
	},
	init:function(lat, lng, zoom, type, mbr) {
		if (GBrowserIsCompatible()) {
			// crea un  mapa
			var map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.addMapType(G_PHYSICAL_MAP);
			map.enableScrollWheelZoom();
			
			var center = new GLatLng(lat, lng);
			
			if (type == null) {
				type = Map.defaultType;
			}
			type = eval(type);
			map.setMapType(type);
			if (mbr != null) {
				zoom = parseInt(map.getBoundsZoomLevel(mbr)-1);
				map.setCenter(mbr.getCenter(), zoom);
			} else {
				map.setCenter(center, zoom);
			}
			return map;
		}
	},
	getMBR:function () {
		// coordenadas extremas
		var swlat = document.getElementById("swlat").value;
		var swlng = document.getElementById("swlng").value;
		var nelat = document.getElementById("nelat").value;
		var nelng = document.getElementById("nelng").value;
		
		var sw = new GLatLng(swlat, swlng);
		var ne = new GLatLng(nelat, nelng);
		
		var mbr = new GLatLngBounds(sw,  ne)
		return mbr;
	}
}
