var hotels = [];
var ipoints = [];

window.addEvent('load', function() {
  HOMaps.init("gmap");
  ResultsMap.init("dyn_gmap");
});


var ResultsMap = {
  map: null,
  bounds: null,
  markers: [],
  div: null,
  request: null,
  init: function(id) {
    if (!$(id)) return;

    ResultsMap.bounds = null;

    ResultsMap.createMap(id);
    ResultsMap.setHotels();
  }, 
  createMap: function(id) {
    if (GBrowserIsCompatible()) {
      ResultsMap.div = $(id);
      ResultsMap.map = new GMap2($(id));
      ResultsMap.map.enableScrollWheelZoom();
      ResultsMap.map.addControl(new GLargeMapControl3D());
      ResultsMap.map.addControl(new GMenuMapTypeControl());
    }
  },
  centerAt: function(hotel) {
    for (var key in window.geodata) {
      var hh = window.geodata[key];
      if (hh == null) continue;

      if (hh.id == hotel.id) {
        hh.marker.show();
      } else {
        hh.marker.hide();
      }
    }
    ResultsMap.map.setCenter(new GLatLng(hotel.lat, hotel.lng), 15);
  },
  setHotels: function() {
    if (ResultsMap.map) {
      ResultsMap.markers = [];
      ResultsMap.map.clearOverlays();
      for (var key in window.geodata) {
        var hotel = window.geodata[key];
        if (hotel !== null && hotel.cat) {
          ResultsMap.addHotel(hotel);
        }
      }
    }
  },
  addHotel: function(hotel) {
    var cat = "dondedormir" + ((hotel.cat.test(/\dEST/))? "_" + hotel.cat: "");
    hotel.marker = ResultsMap.addMarker(hotel.lat, hotel.lng, "", cat, hotel.id, hotel.name);
  },
  addMarker: function(lat, lng, content, cat, idh, name) {
      if (cat==null || cat==undefined) return null;
      var icon = ResultsMap.getIcon(cat);
      var point = new GLatLng(lat,lng);
      var marker = new GMarker(point, { icon: icon, hide: false, title: name });
      /*
      if (isHotel) {
              GEvent.addListener(marker, "click", function() { 
                      if (ResultsMap.request!=null) ResultsMap.request.cancel();
                      HOMaps.balloonMarker = marker;				
                      marker.openInfoWindow(content);
                      HOMaps.request = new Request({
                              method: 'GET', url: HOMaps.cnf.hotelBalloonURL +
                                          '?ajx=true&map=true&codeHotel=' + idh +
                                          '&r=' + Math.random(), 
                              onSuccess: HOMaps.showBalloon
                      }).send();
              });
      } else {
              GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(content) });
      }
      */

      ResultsMap.map.addOverlay(marker);
      return marker;
  },
  /*
  showBalloon: function(res) {
          res = res || HOMaps.res;
          if (!$("balloon")) { HOMaps.res=res; setTimeout(HOMaps.showBalloon, 50); return; }
          $("balloon").set("html", res);
          HOMaps.balloonMarker.openInfoWindowHtml(res);
          $$("#balloon_menu a").each(function(i) {
                  i.removeEvents(['click']);
                  i.addEvent("click", HOMaps.hotelTab);
          });
  },
  hotelTab: function(ev) {
          $$("#balloon .bl_tab").each(function(i) { 
                  (ev.target.rel == i.id)? i.removeClass("closed") : i.addClass("closed"); 
          });
          HOMaps.updateInfoWindow(HOMaps.balloonMarker);
  }, 
  */
  getCenter: function(list,lat,lng) {
          var mlat=0, mlng=0, invalid=0;
          list.each(function(i) {
                  var lt = parseFloat(i[lat],0), lg = parseFloat(i[lng],0);
                  if (lt==0 ||lg==0) invalid++
                  else { mlat += lt; mlng += lg; }
          });
          var center = new GLatLng(mlat/(list.length-invalid), mlng/(list.length-invalid));
          return center;
  },
  icons: { },
  // Icons
  getIcon: function(name) {
          if (ResultsMap.icons[name] != null) return ResultsMap.icons[name];
          // var path = ResultsMap.cnf.iconPaths[name];
          var path = staticServerPath + "/" + ResultsMap.cnf.iconPath.replace(/{type}/, name);
          if (path == null) path = ResultsMap.cnf.iconPaths['default'];
          var icon = new GIcon();
          icon.image = path;
          icon.shadow = ResultsMap.cnf.iconShadow;
          icon.iconSize = new GSize(21, 32);
          icon.shadowSize = new GSize(36, 34);
          icon.iconAnchor = new GPoint(11, 32);
          icon.infoWindowAnchor = new GPoint(5, 2);
          icon.infoShadowAnchor = new GPoint(20, 19);
          icon.printImage = path;
          ResultsMap.icons[name] = icon;
          return ResultsMap.icons[name];
  }, 
  cnf: {
          defZoom: 13,
          iconPath: "img/maps/{type}.png",
          catIconPaths: { dondedormir: "img/maps/filtro_dondedormir.gif", ipoint: "img/maps/filtro_interes.gif", 'default': "img/maps/filtro_otros.png",
                  quever: "img/maps/filtro_interes.gif", transportes: "img/maps/filtro_transporte.png", dondecomer: "img/maps/filtro_dondecomer.png"},
          iconShadow: ssp("{ssp}img/maps/sombra.png"),
          hotelBalloonURL: "/hotelbox.aspx"
  }
}

var HOMaps = {
	map: null,
	bounds: null,
	markers: [],
	categories: [],
	div: null,
	request: null,
	init: function(id) {
		if (!$(id)) return;
		if ($("jsonlist")) hotels = evalJson($("jsonlist").value);
		if ($("interestPointsJson")) ipoints = evalJson($("interestPointsJson").value);
		// $(id).setStyles({height: '500px', width: $("map").getWidth()});

		HOMaps.bounds = null;
		HOMaps.markers = [];
		HOMaps.categories = [];

		HOMaps.createMap(id);
                HOMaps.initCategories(hotels, ipoints);
		HOMaps.catChooser();

		HOMaps.addHotels(hotels);
		HOMaps.addIPoints(ipoints);
		HOMaps.setLocators();
	}, 
	createMap: function(id) {
		if (GBrowserIsCompatible()) {
			HOMaps.div = $(id);
			HOMaps.map = new GMap2($(id));
			HOMaps.map.addControl(new GLargeMapControl());
			HOMaps.map.addControl(new GMapTypeControl());
		}
	},
	initCategories: function(hotels, ipoints) {
		var cat;
		if ($defined(hotels)) {
			HOMaps.categories.push("dondedormir");
		}
		if ($defined(ipoints)) {
			ipoints.each(function(i) {
				cat = i.I.split("_")[0];
				if (HOMaps.categories.indexOf(cat) == -1) {
					HOMaps.categories.push(cat);
				}
			});
		}
	},
	setCenterLatLng: function(lat, lng, zoom) {
		zoom = zoom || HOMaps.cnf.defZoom;
		HOMaps.map.setCenter(new GLatLng(lat, lng), zoom);
	},
	setCenter: function(point, zoom) {
		if (isNaN(point.x)) return;		
		zoom = zoom || HOMaps.cnf.defZoom;
		HOMaps.map.setCenter(point, zoom);
	},
	addHotels: function(list) {
		HOMaps.setCenter( HOMaps.getCenter(list,"lat","lng") );
		// HOMaps.setCenterFromList(list,"lat","lng");
		list.each(function(i) { HOMaps.addHotel(i); });
	},
	addIPoints: function(list) {		
		//HOMaps.setCenter( HOMaps.getCenter(list,"Lt","Lg") );
		// if (list.length > 0) HOMaps.setCenterFromList(list,"Lt","Lg");
		list.each(function(i) { HOMaps.addIPoint(i); });
	},
	addHotel: function(hotel) {
		var content = HOMaps.ballon.loading;
		var cat = "dondedormir" + ((hotel.catCode.test(/\dEST/))? "_" + hotel.catCode: "");
		HOMaps.addMarker(hotel.lat, hotel.lng, content, cat, hotel.id, hotel.name);
	},
	addIPoint: function(ipoint) {
		var content = HOMaps.ballon.ipoint.substitute(ipoint);
		HOMaps.addMarker(ipoint.Lt, ipoint.Lg, content, ipoint.I, ipoint.id, ipoint.N);
	},
	addMarker: function(lat, lng, content, cat, idh, name) {
	    if (cat==null || cat==undefined) return;
	    var icon = HOMaps.getIcon(cat);
	    var point = new GLatLng(lat,lng);
            var isHotel = cat.test(/^dondedormir/);
	    var marker = new GMarker(point, { icon: icon, hide: !isHotel, title: name });
	    if (isHotel) {
		    GEvent.addListener(marker, "click", function() { 
			    if (HOMaps.request!=null) HOMaps.request.cancel();
			    HOMaps.balloonMarker = marker;				
			    marker.openInfoWindow(content);
			    HOMaps.request = new Request({
				    method: 'GET', url: HOMaps.cnf.hotelBalloonURL +
						'?ajx=true&map=true&codeHotel=' + idh +
						'&r=' + Math.random(), 
				    onSuccess: HOMaps.showBalloon
			    }).send();
		    });
	    } else {
		    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(content) });
            }

	    // var marker = HOMaps.createMarker(point, content, icon);
	    if (idh != undefined) marker.idh = idh;
	    var catName = cat.split("_")[0];
	    marker.category = catName;
	    
	    HOMaps.markers.push(marker);
	    HOMaps.map.addOverlay(marker);
	},
	showBalloon: function(res) {
		res = res || HOMaps.res;
		if (!$("balloon")) { HOMaps.res=res; setTimeout(HOMaps.showBalloon, 50); return; }
		$("balloon").set("html", res);
		HOMaps.balloonMarker.openInfoWindowHtml(res);
		$$("#balloon_menu a").each(function(i) {
			i.removeEvents(['click']);
			i.addEvent("click", HOMaps.hotelTab);
		});
	},
	hotelTab: function(ev) {
		$$("#balloon .bl_tab").each(function(i) { 
			(ev.target.rel == i.id)? i.removeClass("closed") : i.addClass("closed"); 
		});
		HOMaps.updateInfoWindow(HOMaps.balloonMarker);
	}, 
	getCenter: function(list,lat,lng) {
		var mlat=0, mlng=0, invalid=0;
		list.each(function(i) {
			var lt = parseFloat(i[lat],0), lg = parseFloat(i[lng],0);
			if (lt==0 ||lg==0) invalid++
			else { mlat += lt; mlng += lg; }
		});
		var center = new GLatLng(mlat/(list.length-invalid), mlng/(list.length-invalid));
		return center;
	},
	setCenterFromList: function(list, lat, lng) {
		HOMaps.map.setCenter(new GLatLng(0,0),0);
		if (HOMaps.bounds == null) HOMaps.bounds = new GLatLngBounds();
		list.each(function(i) { HOMaps.bounds.extend(new GLatLng(i[lat], i[lng])); });
		HOMaps.setCenter(HOMaps.bounds.getCenter(), HOMaps.map.getBoundsZoomLevel(HOMaps.bounds));		
	},
	// Categories	
	catChooser: function(cat) {
                if (HOMaps.categories.length == 0) return;
		var wrapper, head, chooser;
		HOMaps.div.adopt(
			wrapper = new Element("div", {id: "catWrapper"}).adopt(
				head = new Element("div", {id: "catHeader"}).adopt(
                                        new Element("span", { html: CategoryLabels.title })
                                ),
				chooser = new Element("div", {id: "catChooser"})
			)
		); 
		HOMaps.categories.each(function(catName) {
                        var checkbox, label, text;
                        text = CategoryLabels[catName];
                        if (typeof(text) === "undefined") {
                                text = CategoryLabels["otros"];
                        }
                        chooser.grab(new Element("div", {'class': "catCheck"}).adopt(
                                checkbox = new Element("input", {type: "checkbox", id: "catCh_"+catName, value: catName }),
                                label = new Element("label", {'for': "catCh_"+catName}).adopt(
                                        new Element("img", {src: staticServerPath + "/" + HOMaps.cnf.catIconPaths[catName]}),
                                        new Element("span").set("html", text)
                                )
                        ));  
                        checkbox.addEvent("click", function(e) { 
                                (this.checked)? HOMaps.showCat(this.value):HOMaps.hideCat(this.value);
                        });
                        if (catName === "dondedormir") {
                                checkbox.checked = true;
                        }
		});
	},	
	hideCat: function(cat) {
		var list = HOMaps.markers.each(function(i) { if (i.category == cat) i.hide(); });		
	},
	removeCat: function(cat) {		
		HOMaps.markers.each(function(i) { if (i.category == cat) i.remove(); });
		HOMaps.markers = HOMaps.markers.filter(function(i) { return i.category != cat;});
	},
	showCat: function(cat) {		
		var list = HOMaps.markers.each(function(i) { if (i.category == cat) i.show(); });
	},
	icons: { },
	// Icons
	getIcon: function(name) {
		if (HOMaps.icons[name] != null) return HOMaps.icons[name];
		// var path = HOMaps.cnf.iconPaths[name];
		var path = staticServerPath + "/" + HOMaps.cnf.iconPath.replace(/{type}/, name);
		if (path == null) path = HOMaps.cnf.iconPaths['default'];
		var icon = new GIcon();
		icon.image = path;
		icon.shadow = HOMaps.cnf.iconShadow;
		icon.iconSize = new GSize(21, 32);
		icon.shadowSize = new GSize(36, 34);
		icon.iconAnchor = new GPoint(11, 32);
		icon.infoWindowAnchor = new GPoint(5, 2);
		icon.infoShadowAnchor = new GPoint(20, 19);
		icon.printImage = path;
		HOMaps.icons[name] = icon;
		return HOMaps.icons[name];
	}, 
	cnf: {
		defZoom: 12,
		iconPath: "img/maps/{type}.png",
		catIconPaths: { dondedormir: "img/maps/filtro_dondedormir.gif", ipoint: "img/maps/filtro_interes.gif", 'default': "img/maps/filtro_otros.png",
			quever: "img/maps/filtro_interes.gif", transportes: "img/maps/filtro_transporte.png", dondecomer: "img/maps/filtro_dondecomer.png"},
		iconShadow: ssp("{ssp}img/maps/sombra.png"),
		hotelBalloonURL: "/hotelbox.aspx"
	},  
	ballon: {		
		ipoint: '<div id="blpi_{id}"><h2>{N}</h2></div><div class="content" id="ctpi_{id}">&nbsp;</div></div>',
		loading: ssp("<div id='balloon'><img src='{ssp}img/bigloader.gif' /></div>")
	}, 
	setTpl: function(tpl, id) {
		var hotel = HOMaps.getHotel(id);
		var res = HOMaps.ballon[tpl].substitute(hotel);
		if (tpl == "photos") {
			var images = "";
			hotel.img.each(function(i) { images += HOMaps.ballon.photo.replace("{img}", i); });
			res = res.replace("[images]", images);
		}
		$("ct_" + id).set('html', res);		
		HOMaps.updateInfoWindow(HOMaps.getMarker(id));
	},
	viewHotel: function(id) {
		HOMaps.getMarker(id).fireEvent("click");
	},
	updateInfoWindow: function(marker) {
		var info = HOMaps.map.getInfoWindow();
		var cont = $(info.getContentContainers()[0]);
		info.reset(marker.getLatLng(), 0, new GSize(cont.getWidth(), cont.getElement(".balloon").getHeight()))
	}, 
	getHotel: function(id) {
		var res = hotels.filter(function(i) { return i.id = id });
		if (res.length == 0) return {};
		return res.pop();
	},
	getMarker: function(id) {
		var res = HOMaps.markers.filter(function(i) { return i.idh == id});
		if (res.length == 0) return {};
		return res.pop();
	},
	setLocators: function() {
		$$("a.loc_map").each(function(i) {
			i.addEvent("click", function(ev) {
				ev.stop();
				GEvent.trigger(HOMaps.getMarker(i.rel), "click");
				location.hash = "content";
			})
		});
	}
}

function GUnload() {
	try{ if (window.GUnloadApi) GUnloadApi(); }
	catch(e) {};
}
