$(document).ready(function() {
  loadGoogleMaps();
  $(window).unload(GUnload);

  $("#buscar_direccion_button").click(function() {
	geocodeAddress($("#buscar_direccion").val());
  });

  $("#buscar_direccion").bind("keypress", function(evt) {
    var charCode = (evt.which) ? evt.which : window.event.keyCode;
    if (charCode == 13)
		geocodeAddress($("#buscar_direccion").val());
  });
})

var map;

function loadGoogleMaps() {
  if (GBrowserIsCompatible()) {
  	map = new GMap2(document.getElementById("map"));
	new ContextMenu(map);
	map.setCenter(new GLatLng(39.954490, 4.053955), 11);

	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	//map.addControl(new GOverviewMapControl());
	map.enableScrollWheelZoom();

    getLocations();
  }
}

function getLocations(){
	map.clearOverlays();

	var bounds = new GLatLngBounds();
	for (var i = 0; i < empresas.length; i++) {
		var point = new GLatLng(parseFloat(empresas[i].lat), parseFloat(empresas[i].lng));
		var marker = createMarker(point, empresas[i].id, empresas[i].nombre, empresas[i].direccion, empresas[i].web, empresas[i].telefono, empresas[i].horario, empresas[i].temporada, i+1);

		hookEventsToMarker(document.getElementById('item_empresa_' + (i+1)), marker);

		map.addOverlay(marker);
		bounds.extend(point);
	}

	map.setCenter(new GLatLng(39.927049950707, 4.0543359518051), 10);

	/*if (bounds.getSouthWest().lng() != 180)
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));*/
}

function hookEventsToMarker(item, marker) {
	$(item).parent().click(function() {
		map.setCenter(marker.getLatLng());
		GEvent.trigger(marker, 'click');
		return false;
	}).mouseover(function() {
		$(item).parent().addClass("over");
	}).mouseout(function() {
		$(item).parent().removeClass("over");
	})
}

function createMarker(point, comercio_id, nombre, direccion, web, telefono, horario, temporada, numero){

	var marker = new GMarker(point, {draggable: enableDragging, autoPan: false});

	if (numero && (numero < 100))
		marker.getIcon().image = "/images/icons/gmaps/marker" + numero + ".png";
	else
		marker.getIcon().image = "/images/icons/gmaps/marker.png";

	GEvent.addListener(marker, 'click', function(){
		var contentDiv = document.createElement('div');
		contentDiv.className = "map_marker_info";
        contentDiv.innerHTML = 'Cargando...'

        var iw = map.getInfoWindow();
		GDownloadUrl("/comercios_ajax/storeInfo/store_id/" + comercio_id, function(data){
			contentDiv.innerHTML = data;
			marker.openInfoWindowHtml(contentDiv);
		});

		return false;
	});;

	if (enableDragging) {
		GEvent.addListener(marker, "dragstart", function(){
			map.closeInfoWindow();
		});

		var postUrl = "/comercios_ajax/changePosition";
		GEvent.addListener(marker, "dragend", function(){
			/* Avisam al servidor de la nova posició */
			var position = marker.getLatLng();
			$.post(postUrl, {
				id: comercio_id,
				lat: position.lat(),
				lng: position.lng()
			}, function(data){
				if (data == "ok")
					alert("El comercio se ha posicionado correctamente");
				else
					alert("ERROR:\n\n" + data);
			});
		});
	}
	return marker;
}

function openInfoWindow(id, opt_point) {
	if (gApplication && id != "") {
		gApplication.openInfoWindow(id, opt_point);
		return false;}
	return true;
}

function centerMap(point) {
	if (point)
		map.setCenter(point);
	else
		alert("No se ha podido resolver la dirección especificada.")
}

function geocodeAddress(address) {
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, centerMap);
}

/* MENÚ CONTEXTUAL */
function ContextMenu(oMap){this.initialize(oMap);}

//Construct the DOM tree of the menu
ContextMenu.prototype.initLink = function(oMap){
	var that=this;
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Obtener posición</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.contextmenu.style.display = "none";
		alert(point.lat() + ", " + point.lng());
	});
	this.ul_container.appendChild(a_link);

	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>Obtener dirección de esta posición</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		geocoder = new GClientGeocoder();
		that.contextmenu.style.display = "none";
		geocoder.getLocations(point, showAddress);
	});
	this.ul_container.appendChild(a_link);
}

//The object 'constructor'
ContextMenu.prototype.initialize = function(oMap){
	this.map = oMap;
	var that = this;

	this.contextmenu = document.createElement("div");
	this.contextmenu.style.display = "none";
	//CSS class name of the menu
	this.contextmenu.className = "contextmenu";
	this.ul_container = document.createElement("ul");
	this.ul_container.id = "context_menu_ul";
	this.contextmenu.appendChild(this.ul_container);
	this.initLink();
	this.map.getContainer().appendChild(this.contextmenu);

	//Event listeners that will interact with our context menu
	GEvent.addListener(oMap, "singlerightclick", function(pixel, tile){
		that.clickedPixel = pixel;
		var x = pixel.x;
		var y = pixel.y;
		//Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
		if (x > that.map.getSize().width - 160) {
			x = that.map.getSize().width - 160
		}
		if (y > that.map.getSize().height - 120) {
			y = that.map.getSize().height - 120
		}
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x, y));
		pos.apply(that.contextmenu);
		that.contextmenu.style.display = "";
	});
	GEvent.addListener(oMap, "move", function(){
		that.contextmenu.style.display = "none";
	});
	GEvent.addListener(oMap, "click", function(overlay, point){
		that.contextmenu.style.display = "none";
	});
}

function showAddress(response) {
  if (!response || response.Status.code != 200) {
    alert("No se ha podido obtener la direcicón de este punto");
  } else {
    place = response.Placemark[0];
    alert(place.address);
  }
}
