﻿/*
 * TODO:
 * 		Creo que deberíamos mirar si se pueden tener los conjuntos de marcadores especiales (extra) como
 * 		parte de un plugin. De forma que realmente se carguen con dicho plugin y no de otra forma. Podemos
 * 		considerar que dicho plugin internamente tiene todo lo necesario para cargarlo directamente en el
 * 		addPlugins o que es un plugin de otro estilo y requiere su propio método de inicialización.
 *
 * 		En cualquier caso la idea es mantener los conjuntos de clusters y de objetos marcadores especiales
 * 		separados del tratamiento general del API. De forma que podamos expandir los objetos de la definición
 * 		o sustituirlos totalmente.
 *
 * 		Estos datos de objetos y estilos de marcadores especiales pueden ir separados en otros ficheros de javascript
 * 		de forma que el propio servidor pueda mandar un código u otro dependiendo del campus en el que nos encontremos
 * 		y así tener un control personalizado de los tipos de marcadores especiales que hay.
 * 		El control y la función de consulta para los marcadores vendría dada por el servidor para ese cliente.
 * 		De forma que extenderían o sobreescribirían la parte del API que necesite cada uno.
 *
 * 		Otra opción es hacer que el plugin tome los datos de los servicios para ese cliente y los recorra de forma
 * 		que se genere dinámicamente el menú contextual de checks en base a los datos que contiene. (es factible)
 */
/**
 * Main Accessia API Definition
 * @author Andrés Gustavo Soto Vidal. Digio Soluciones.
 * @version 0.2 beta
 * @projectDescription Este API pretende simplificar el uso del mapa de google añadiendo funcionalidades y controles, de forma que el usuario de la misma no tenga que preocuparse de nada. O casi de nada.
 */

/**
 * @class Accessia
 * @alias Accessia_v2
 * @param {object} options A block of options for GMap subobject and Livemap subobject.
 * @constructor
 */
function Accessia_v2(options) {
	this.version = 'version 0.2 beta';
	this.Gmap = new Accessia_v2_Gmap(options.Gmap);
	this.Livemap = null;
}
/*
 *	PLUGIN ADITION FUNCTION
 */
/**
 * @alias addPlugins
 * @param {Object} options Objeto con los plugins que serán añadidos al API.
 * @memberOf Accessia_v2
 * @method
 */
Accessia_v2.prototype.addPlugins = function(options){
	var that = this;
	$.each(options, function(target){
		that[target].addPlugins(options[target]);
	});
}

/*
 *	Accessia_Gmap_Class
 */
/**
 * @alias Gmap
 * @param {Object} options
 * @memberOf Accessia_v2
 */
function Accessia_v2_Gmap(options) {
	var that = this;
	/*** 	DEFAULT NOT EDITABLE VARS 	***/
	this._imageRoute = 'http://accessia.es/jqmaps/maps_imgs/Tile_';	//Accessia normal
	//imageRoute = "http://beta.accessia.es/jqmaps/maps_imgs/";
	this._map = null;
	this._geocoder = null;
	this._gears = null;
	this._final_location = null;
	this._last_marker = null;
	this._ciencias_salud_image_route = "umu_ciencias_salud/";
	this._merced_image_route = "umu_merced/";
	this._base_kml_route = "http://beta.accessia.es/assets/";
	this._entrada_campus = "38.019160 -1.166390";
	this._markers_route = "/assets/xml/data.xml";
	this._planos_base = "/imgs/PlanosUM/";
	this._http_service = "/service/services/";
	this._blank_links_class = "_ACCESSIA_GMAP_BLANK_LINKS_";
	this._google_print = "/printer/gprint/";

	/****	DEFAULT EDITABLE VARS	****/
	this._accessia_zoom = 16;
	this._accessia_min_zoom = 6;
	this._accessia_max_zoom = 17;
	this._max_ancho_direcciones = 230;
	this._max_ancho_animacion = 190;
	this._ajuste_mapa_W = 15;
	this._ajuste_mapa_H = 45;
	this._lightbox = null;
	this._library = null;
	this._lightBoxPlusOptions = {
		loadingimg:'js/lightbox_plus/loading.gif',
		expandimg:'js/lightbox_plus/expand.gif',
		shrinkimg:'js/lightbox_plus/shrink.gif',
		previmg:'js/lightbox_plus/prev.gif',
		nextimg:'js/lightbox_plus/next.gif',
		/*effectimg:'js/lightbox_plus/zzoop.gif',*/
		effectpos:{x:-40,y:-20},
		effectclass:'effectable',
		closeimg:'js/lightbox_plus/close.gif',
		resizable:true,
		expandable:true
	};
	this._lightwindow = null;
	this._gdir = null;
	this._infoWindowOptions = null;
	this._infoWindow = null;
	this._geoXml = null;
	this._userIP = null;
	this._userLocation = null;
	this._temporalLocation = null;
	this._geocoder = null;
	this._contextmenu = null;
	this._IE_flag_resize = 0;
	this._IE_flag_directions = 0;
	this._IE_flag_timeout = 0;
	this._initialPositionHandler = null;
	this._keyhandler = null;
	this._GB_ANIMATION = true;
	this._marcador_destino = null;
	this._marcador_inicio = null;
	this._maximizeEnd = null;
	this._maximizeEndHandler = null;
	this._closeclick_restoreclick = null;
	this._maximizeRestoreEndHandler = null;
	this._maximizeCloseClickHandler = null;

	handleErrors = function(){
	   if (that._gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		 alert("No se ha podido encontrar una localizaci&oacute;n con dicho nombre o existe m?s de una.\nError code: " + that._gdir.getStatus().code);

	   else if (that._gdir.getStatus().code == G_GEO_SERVER_ERROR)
		 alert("La localizaci&oacute;n no se ha podido procesar correctamente, causa desconocida.\n Error code: " + that._gdir.getStatus().code);

	   else if (that._gdir.getStatus().code == G_GEO_MISSING_QUERY)
		 alert("Usted introdujo una direcci&oacute;n no v&oacute;lida o una l&iacute;nea en blanco.\n Error code: " + that._gdir.getStatus().code);

	   else if (that._gdir.getStatus().code == G_GEO_BAD_KEY)
		 alert("Error en el ApiKey. \n Error code: " + gdir.getStatus().code);

	   else if (that._gdir.getStatus().code == G_GEO_BAD_REQUEST)
		 alert("La direcci&oacute;n no se ha podido resolver, posiblemente est&aacute; mal escrita o no se ha podido parsear correctamente.\n Error code: " + that._gdir.getStatus().code);

	   else alert("Error desconocido. Puede que haya escrito mal la direcci&oacute;n");
	}

	//VARIABLES PARA OVERLAYS DE INFORMACION
/*	this._bibliotecas = [];
	this._comedores = [];
	this._cafeterias = [];
	this._bancos = [];
	this._paradabuses = [];
	this._hoteles_convenio = [];*/
	//OBJETOS ESPECIALES PARA LOS KMLs
	this._KMLS = {
		'TRANVIA' : {
			'overlay' : null,
			'url' : this._base_kml_route+'linea_tranvia.kml',
			'visible' : false
		},
		'BICI' : {
			'overlay' : null,
			'url' : this._base_kml_route+'carril_bici.kml',
			'visible' : false
		},
		'ACTUACIONES' : {
			'overlay' : null,
			'url' : this._base_kml_route+'nuevas_actuaciones.kml',
			'visible' : false
		}
	}
	this._markerOptions = {};

	//VARIABLES Y FUNCIONES PARA MARCADORES DINAMICOS
	this._littleIcon = new GIcon(G_DEFAULT_ICON);
	this._bigIcon = new GIcon(G_DEFAULT_ICON);
	this._conjuntos = {
		"BIBLIOTECA":[],
		"COMEDOR":[],
		"CAFETERIA":[],
		"BANCO":[],
		/*"TPS":[],*/
		"PARADABUS":[],
		"HOTELCONVENIO":[],
		"PARKING" : []
	}
	this._clustersMaxZoom = 16;
	this._clustersGridSize = 40;
	this._clusters = {
		"BIBLIOTECA" : null,
		"COMEDOR" : null,
		"CAFETERIA" : null,
		"BANCO" : null,
		"PARADABUS" : null,
		"HOTELCONVENIO" : null,
		"PARKING" : null
	}
	this._clusters_visibility = {
		"BIBLIOTECA" : false,
		"COMEDOR" : false,
		"CAFETERIA" : false,
		"BANCO" : false,
		"PARADABUS" : false,
		"HOTELCONVENIO" : false,
		"PARKING" : false
	}


	this._geocoder = new GClientGeocoder();
	this._littleIcon.iconSize = new GSize(20,20);
	this._littleIcon.shadowSize = new GSize(0,0);
	this._littleIcon.iconAnchor = new GPoint(20,10);
	this._littleIcon.infoWindowAnchor = new GPoint(10,2);
	this._bigIcon.iconSize = new GSize(32,32);
	this._bigIcon.shadowSize = new GSize(0,0);
	this._bigIcon.iconAnchor = new GPoint(20,10);
	this._bigIcon.infoWindowAnchor = new GPoint(10,2);
	this._iconos = {
		"BIBLIOTECA":new GIcon(this._littleIcon,"/imgs/bibliotecaIcon.png"),
		"COMEDOR":new GIcon(this._littleIcon,"/imgs/comedorIcon.jpg"),
		"CAFETERIA":new GIcon(this._littleIcon,"/imgs/cafeteriaIcon.gif"),
		"BANCO":new GIcon(this._littleIcon,"/imgs/bancoIcon.jpg"),
		/*"TPS":new GIcon(littleIcon,"./imgs/tpsIcon.png"),*/
		"PARADABUS":new GIcon(this._littleIcon,"/imgs/paradabusIcon.jpg"),
		"PARKING":new GIcon(this._littleIcon,"/images/parking.png"),
		"EDIFICIO":new GIcon(this._bigIcon,"/imgs/building.gif"),
		//"EVENTO":new GIcon(bigIcon,"./imgs/universitario.gif",	HA CAMBIADO
		"EVENTO":new GIcon(this._bigIcon,"/imgs/target.png"),
		"START":new GIcon(this._bigIcon,"/imgs/a_inicio.gif"),
		"HOTELCONVENIO":new GIcon(this._bigIcon,"/imgs/hotel.gif")
	};

	this._regenerarLightBoxPlus = function(){
		this._lightbox = new LightBox(this._lightBoxPlusOptions);
	};
	this._regenerarLightWindow = function(){
		this._lightwindow = new lightwindow();
	};


	this._maximizeEnd = {
		place : function(){
			$("a","."+this._blank_links_class).attr("target", "_blank");
			$('#_link_searchlocation').unbind('click').click(function(){
				that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location,'es');return false;
			});
			that._regenerarLightBoxPlus();
		},
		partnerevent : function(){
			setTimeout(function(){
				$("a","."+that._blank_links_class).attr("target", "_blank");
				$('#_link_searchlocation').unbind('click').click(function(){
					that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location,'es');return false;
				});
			}, 500);
		}
	}

	this.copyRight = new GCopyrightCollection('Callejero').addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0," 2008 Digio S.L."))

	if (typeof(google)!='undefined' && typeof(google.gears)!='undefined') this._gears = google.gears.factory.create('beta.geolocation');

	if (typeof (options.map === 'object')){
		this._map = options.map;						// Referencia al mapa
		if (typeof(options.directions_div)!='undefined' && options.directions_div !=""){
			this._gdir = new GDirections(this._map, document.getElementById(options.directions_div));
			GEvent.addListener(this._gdir, "error", this.handleErrors);
			GEvent.addListener(this._gdir, "load", ( (typeof(options.onDirectionsLoad)!='undefined' && options.onDirectionsLoad )?options.onDirectionsLoad:Accessia.Gmap.onGDirectionsLoad));
		}
		if (typeof(options.onHomeDrop)!='undefined' && options.onHomeDrop) this._onHomeDrop = options.onHomeDrop;
		if (options.active_layers) this.init_layers(this._map);
		if (options.active_map_types) this.init_map_types(this._map);
		if (options.active_location) this.initLocation(null);
		if (options.streetDrop) this._street_doll_drop = options.streetDrop;
		if (options.zoomLevels && typeof(options.zoomLevels)=='object'){
			this._accessia_min_zoom = options.zoomLevels.minLevel;
			this._accessia_max_zoom = options.zoomLevels.maxLevel;
			
			var minMapScale = this._accessia_min_zoom; 
			var maxMapScale = this._accessia_max_zoom; 
			// get array of map types 
			var mapTypes = this._map.getMapTypes(); 
			// overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type 
			for (var i=0; i<mapTypes.length; i++) {
				console.log(mapTypes[i]);
				mapTypes[i].getMinimumResolution = function() {return minMapScale;} 
				mapTypes[i].getMaximumResolution = function() {return maxMapScale;} 
			}
		}
		if (options.setCenter && typeof(options.setCenter)=='object'){
			this._map.setCenter(new GLatLng(options.setCenter.lat, options.setCenter.lng), this._accessia_zoom);
		}
	}else return false;

	if (typeof(options.load_overlays)!='undefined'){
		if (typeof(options.load_overlays.ground_overlays)!='undefined'){
			this.loadGroundOverlays(options.load_overlays.ground_overlays);
		}
	}
}
/*
 *	ACCESSIA GMAP CLASS METHODS
 */
Accessia_v2_Gmap.prototype.loadMapLayer = function(){
	this._map.addOverlay(new GLayer("com.panoramio.all"));
}

Accessia_v2_Gmap.prototype._loadKML = function(tipo){
	if (this._KMLS[tipo].overlay != null){
		this._map.removeOverlay(this._KMLS[tipo].overlay);
		this._map.addOverlay(this._KMLS[tipo].overlay);
		this._KMLS[tipo].overlay.gotoDefaultViewport(this._map);
		this._KMLS[tipo].visible = true;
	}else{
		var that = this;
		var geoxml = new GGeoXml(this._KMLS[tipo].url+"?"+(new Date()).getTime(), function(){
			that._KMLS[tipo].overlay = geoxml;
			that._map.addOverlay(geoxml);
			that._KMLS[tipo].overlay.gotoDefaultViewport(that._map);
			that._KMLS[tipo].visible = true;
		});
	}
};
Accessia_v2_Gmap.prototype._removeKML = function(tipo){
	if (this._KMLS[tipo].overlay != 'undefined'){
		this._map.removeOverlay(this._KMLS[tipo].overlay);
		this._KMLS[tipo].visible = false;
	}
};
Accessia_v2_Gmap.prototype._changeMapZoom = function(zoom, center){
	this._map.setZoom(zoom);
	this._map.panTo(center);
};
Accessia_v2_Gmap.prototype._writeInfoPanel = function(marker){
	marker.openInfoWindowHtml("" +
			"Nueva posici&oacute;n seleccionada<br>" +
			"<a class=\"_info_window\" href='#'>Calcular ruta...</a>");
	var that = this;
	if (marker.clickHandler) GEvent.removeListener(marker.clickHandler);
	marker.clickHandler = GEvent.addListener(marker, 'infowindowopen', function(){
		$("._info_window").unbind('click').click(function(){
			that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location, 'es');
		});
	});
};
Accessia_v2_Gmap.prototype._addMarkers = function(tipo){
	if (tipo == null || tipo === 'undefined' || typeof tipo === 'undefined') return false;
	else if (typeof(this._conjuntos[tipo]) === 'undefined') return false;
	if (this._conjuntos[tipo].length == 0) this._loadMarkers(tipo);
	for(i = 0; i < this._conjuntos[tipo].length; i++) this._map.addOverlay(this._conjuntos[tipo][i]);
};
Accessia_v2_Gmap.prototype._removeMarkers = function(tipo) {
	if (tipo == null || tipo === 'undefined' || typeof tipo === 'undefined') return false;
	else if (typeof(this._conjuntos[tipo]) === 'undefined') return false;
	for(i = 0; i < this._conjuntos[tipo].length; i++) this._map.removeOverlay( this._conjuntos[tipo][i] );
};
//FUNCIONES PARA MARKERS CON TABS
Accessia_v2_Gmap.prototype._createMarkerTabs = function(obj){
	var tabs = new Array();
	if (typeof(obj.tab)==='undefined') return tabs;

	var route_html = '<hr /><a class="_info_window" href="#">Calcular ruta...</a>';

	if (obj.tab.length > 0){
		for (i = 0; i < obj.tab.length; i++){
			var newTab = new GInfoWindowTab(obj.tab[i].label, obj.tab[i].content + route_html);
			tabs.push(newTab);
		}
	}else{
		var newTab = new GInfoWindowTab(obj.tab.label, obj.tab.content + route_html);
		tabs.push(newTab);
	}

	return tabs;
};
/*	TODO :: echarle un ojo para pasar por ejemplo un objeto como parámetro con los datos dentro y poder evaluar un posible undefined, sin que esté como parámetro en la función	*/
Accessia_v2_Gmap.prototype._createMarker = function(i, obj, markers, lat, lng, options){
	var marker = new GMarker(new GLatLng(parseFloat(lat), parseFloat(lng)), options);
	//Le incrustamos un identificador
	marker.marker_num = i;
	marker.marker_type = obj.type;
	marker.max = ( (obj.max)?obj.max:null );
	marker.tabs = this._createMarkerTabs(obj);
	//Almacenamos el marker
	markers[i] = marker;
	var that = this;

	GEvent.addListener(markers[i], "click", function(){
		marker.openInfoWindowTabsHtml(markers[i].tabs, {maxContent:marker.max});
		that._final_location = marker.getLatLng();
		$("._info_window").unbind('click').click(function(){
			that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location, 'es');
		})
	});
	return marker;
};
/*	TODO :: echlarle un ojo para pasar por ejemplo un objeto como parámetro con los datos dentro y poder evaluar un posible undefined, sin que esté como parámetro en la función	*/
Accessia_v2_Gmap.prototype._loadMarkers = function(tipo){
	/*VERSION PARA BASE DE DATOS */
	if (tipo === 'undefined' || tipo === '' || typeof(tipo) === 'undefined') return false;

	var data = new JKL.ParseXML(this._http_service+tipo+".html");
	/* VERSION CON XML
	var data = new JKL.ParseXML(Accessia.Gmap._markers_route);
	*/
	var xml = data.parse();
	var i = 0;
	var j = 0;
	var o = new Object();
	var conjunto = null;
	if (xml.data.location.length > 1){
		for (i=0; i < xml.data.location.length; i++){
			o = xml.data.location[i];
			var marker = this._createMarker(this._conjuntos[o.type].length, o, this._conjuntos[o.type], o.lat, o.lng, {icon:this._iconos[o.type]});
		}
	}else{
		o = xml.data.location;
		var marker = this._createMarker(this._conjuntos[o.type].length, o, this._conjuntos[o.type], o.lat, o.lng, {icon:this._iconos[o.type]});
	}
};
Accessia_v2_Gmap.prototype._createTabbedMarker = function(latlng, id, min, sum, tabs, taboptions, markeroptions){
	  var _marker = new GMarker(latlng, ((markeroptions)?markeroptions:{}));
	  _marker.min = min;
	  _marker.overlay = null;
	  _marker.sum = sum;
	  _marker.id = id;
	  _marker.tabs = tabs;
	  _marker.taboptions = taboptions;

	  var that = this;

/*
		GEvent.addListener(_marker, "click", function(){
			var html = "<div>"+_marker.min+"</div>";
			if (typeof (MyOverlay) != 'undefined') {
				if (typeof(that._marcador_destino.overlay)!='undefined' && that._marcador_destino.overlay) that.closeOverlay(that._marcador_destino);
				if (typeof(this.overlay)==='undefined' || !this.overlay) this.overlay = new MyOverlay(this, html);
				that._map.panTo(latlng);
				that._map.addOverlay(this.overlay);
			}else this.openInfoWindowHtml(html);
		});
*/

/*		  GEvent.addListener(_marker, "click", function() {
		  if (typeof MyOverlay !== 'undefined') {
			if (that._marcador_destino.overlay) {
			  that.closeOverlay(that._marcador_destino);
			}
			if (!this.overlay) {
			  // just recording this for use in the closeOverlay function
			  this.overlay = new MyOverlay(this, html);
			}
			//currentMarker = this;
			that._map.panTo(latlng);
			that._map.addOverlay(this.overlay);
			//this.hide();
		  } else {
			this.openInfoWindowHtml(html);
		  }
		});*/


	  GEvent.addListener(_marker, 'click', function(){
		_marker.openMaxContentTabsHtml(that._map, _marker.min, _marker.sum, _marker.tabs, _marker.taboptions);
	  });

	  _marker.resize = $(window).resize(function(){
		that._map.getTabbedMaxContent().checkResize();
	  });

	  return _marker;
};
/* 	TODO :: revisar entera y modificar para dar generecidad  --- Interesante ver si se puede generar un marcador con todos los tabs que queramos. Pasar un objeto en lugar de un grupo de parámetros, que el objeto contenga los tabs en forma de array por ejemplo */
Accessia_v2_Gmap.prototype.cambiarDestino = function(e){
	if (typeof(e)==='undefined') return false;

	if (this._marcador_destino != null) {
		if (typeof(this._last_marker_is_fixed)!='undefined') {
			if( !this._last_marker_is_fixed ) {
				if (this._marcador_destino.overlay) { this.closeOverlay(this._marcador_destino); }
				this._map.removeOverlay(this._marcador_destino);
			}
		}else{
			this._map.removeOverlay(this._marcador_destino);
		}
	}

	var id_ = e.name+((new Date()).getTime());
	var _icon = null;
	var infoString = "<br>Se ha establecido:<br>"+
	 "<b>"+e.name+"</b><br>Como lugar de destino<br>"+ /* he cambiado simpleContent por name */
	 //"<br><a href='#' id='_link_searchlocation' class='no_blank_' onclick='Accessia.Gmap.searchLocation(Accessia.Gmap._userLocation.lat()+\" \"+Accessia.Gmap._userLocation.lng(),Accessia.Gmap._final_location,\"es\");return false;'>Calcular ruta...</a>";
	 "<br><a href='#' id='_link_searchlocation' class='no_blank_' >Calcular ruta...</a>";
	infoString += "<p>&nbsp;</p>";
	var full_infoString = infoString;
	var planosPlanta = new Array();
	var tabs = new Array();
	var that  = this;

	switch(e.type){
		case "place" :
			_icon = this._iconos["EDIFICIO"];
			if (e.description) infoString += e.description;
			tabs.push(new MaxContentTab("Informaci&oacute;n", '<div class="'+this._blank_links_class+'">'+infoString+'</div>'));
			var plantas = eval(e.plantas);
			if (plantas.length>0){
				var htmlPlantas = "<ul>";
				for (i=0; i<plantas.length; i++){
					htmlPlantas+="<li><a href='"+this._planos_base+plantas[i].value+"' rel='lightbox' class='effectable' title='"+plantas[i].name+"'>"+plantas[i].name+"</a></li>";
				}
				htmlPlantas += "</ul>";
				tabs.push(new MaxContentTab("Plano", htmlPlantas));
			}
			break;
		case "partnerevent" :
			_icon = this._iconos["EVENTO"];
			if (e.description != undefined){
				full_infoString = infoString + "<hr><br>"+'<div class="'+this._blank_links_class+'">'+e.description+'</div>';
				tabs.push(new MaxContentTab("Informaci&oacute;n", full_infoString));
			}
			break;
		default : new GIcon(); break;
	}

	/* Esto añade los tabs que queramos */
	if (e.tabs != 'undefined' && e.tabs){
		for (var i = 0; i < e.tabs.length; i++) {
			tabs.push(new MaxContentTab(e.tabs[i].title, '<div class="'+this._blank_links_class+'">'+e.tabs[i].content+'</div>'));
		}
	}

	/* TEMA DEL ICONO NUEVO */
	if (typeof(e.myIconUrl)!='undefined'){
		if (e.myIconUrl != ""){
			_icon = new GIcon(this._littleIcon, e.myIconUrl);
		}
	}

	var parking = new GLatLng(e.lat_parking, e.lng_parking);
	var taboptions = {
				maximized : false,
				maxTitle: e.name, 			/* he cambiado simpleContent por name */
				selectedTab : 0,
				closeOnRestore : false
				//maximizeEnd : this._maximizeEnd[e.type]
			}

	this._marcador_destino =
		this._createTabbedMarker(
			new GLatLng( e.lat, e.lng ),
			id_, infoString,  '',  tabs, taboptions,{
				icon : _icon, draggable : false
			}
		);

	/* POR ALGUNA RAZON NO FUNCIONA AHORA EL CALLBACK DEL MAXIMIZE EN EL CREATE TABBEDMARKER, SEGURAMENTE ESTOY PASANDO ALGO MAL */
	if (this._maximizeEndHandler) GEvent.removeListener(this._maximizeEndHandler);
	this._maximizeEndHandler = GEvent.addListener(this._map.getInfoWindow(), "maximizeend", this._maximizeEnd[e.type]);
	/* POR ALGUNA RAZON NO FUNCIONA AHORA EL CALLBACK DEL MAXIMIZE RESTORE.... pues como antes... */
	if (this._maximizeRestoreEndHandler) GEvent.removeListener(this._maximizeRestoreEndHandler);
	this._maximizeRestoreEndHandler = GEvent.addListener(this._map.getInfoWindow(), "restoreclick", function(){
		that._map.getInfoWindow().hide();
		that._map.panTo(that._marcador_destino.getLatLng());
	});
	/* Añadimos más efecto al cerrar el marcador */
	if (this._maximizeCloseClickHandler) GEvent.removeListener(this._maximizeCloseClickHandler);
	this._maximizeCloseClickHandler = GEvent.addListener(this._map.getInfoWindow(), "closeclick", function(){
		that._map.getInfoWindow().hide();
		that._map.setCenter(that._marcador_destino.getLatLng());
		that._map.panTo(that._marcador_destino.getLatLng());
	});


	//INSERTAR EL MARCADOR
	this._last_marker_is_fixed = false;
	this._map.addOverlay(this._marcador_destino);

	//MOSTRAR INICIALMENTE EL GLOBO
	/*
	*ESTO SE QUITA Y SE SUSTITUYE POR UN TRIGGER DE CLICK.
	this._marcador_destino.openMaxContentTabsHtml(this._map, this._marcador_destino.min, '', tabs, taboptions);
	*/
	if (this._openInfoWindowHandler) GEvent.removeListener(this._openInfoWindowHandler);
	this._openInfoWindoHandler = GEvent.addListener(this._map, 'infowindowopen', function(){
		$('#_link_searchlocation').unbind('click').click(function(){
			that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location,'es');return false;
		});
	});
	GEvent.trigger(this._marcador_destino, "click");

	//FINAL_LOCATION
	this._final_location = ((typeof (e.lat_parking)!='undefined')?e.lat_parking:e.lat) + " " + ((typeof (e.lng_parking) !='undefined')?e.lng_parking:e.lng);
	//CENTRAR EL MAPA
	this._map.setCenter(this._marcador_destino.getLatLng());

	return("ok");
};

Accessia_v2_Gmap.prototype._customGetTileUrl = function(a,b){
	var f;
	switch(b) {
		case 13 : if (a.x == 4069 && a.y == 3159) f = Accessia_v2_Gmap.prototype._imageRoute+a.x+"_"+a.y+"_"+b+".jpg";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 14 : if (a.x == 8138 && a.y == 6319) f = Accessia_v2_Gmap.prototype._imageRoute+a.x+"_"+a.y+"_"+b+".jpg";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 15 : if ( ((a.x >= 16276) && (a.x <= 16277)) && ((a.y >= 12636) && (a.y <= 12638)) ) f = Accessia_v2_Gmap.prototype._imageRoute+a.x+"_"+a.y+"_"+b+".jpg";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 16 : if ( ((a.x >= 32552) && (a.x <= 32555)) && ((a.y >= 25272) && (a.y <= 25276)) ) f = Accessia_v2_Gmap.prototype._imageRoute+a.x+"_"+a.y+"_"+b+".jpg";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 17 : if ((a.x >= 65106 && a.x <= 65112) && (a.y >= 50545 && a.y <= 50553)) f = Accessia_v2_Gmap.prototype._imageRoute+a.x+"_"+a.y+"_"+b+".jpg";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		default:  f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
	}
	return f;
}

/*Accessia_v2_Gmap.prototype.tileLayers = [new GTileLayer(this.copyRight , 1, 17)];
Accessia_v2_Gmap.prototype.init_layers = function(map, minlevel, maxlevel){
	this.tileLayers[0].getTileUrl = this._customGetTileUrl;
	var custommap = new GMapType(this.tileLayers, G_NORMAL_MAP.getProjection(), "Callejero", {errorMessage:"No data available"});
	// Set maximum and minumum zoom levels
	custommap.getMinimumResolution = function(){return minlevel;}
	custommap.getMaxiumumResolution = function(){return maxlevel;}
	// End on maximum and minum zoom levels
	
	((map != 'undefined')?map:this._map).addMapType(custommap);
	((map != 'undefined')?map:this._map).setMapType(custommap);
}
*/
Accessia_v2_Gmap.prototype.init_map_types = function(map){
	var o = ((map != 'undefined')?map:this._map);
	o.removeMapType(G_SATELLITE_MAP);
	o.addMapType(G_SATELLITE_MAP);
	o.removeMapType(G_NORMAL_MAP);
	o.removeMapType(G_HYBRID_MAP);
	o.enableScrollWheelZoom();
	o.enableContinuousZoom();
}

Accessia_v2_Gmap.prototype._handleGearsError = function(error){
}

Accessia_v2_Gmap.prototype._gears_init = function(){
	var that = this;
	if (typeof(navigator)!='undefined' && typeof(navigator.geolocation)!='undefined'){
		navigator.geolocation.getCurrentPosition(function(position){
			that._userLocation = new GLatLng(position.coords.latitude, position.coords.longitude);
			if (typeof(that._marcador_inicio)!='undefined'){
				that._marcador_inicio.setLatLng(that._userLocation);
			}else{
				that._marcador_inicio = new GMarker(that._userLocation, {icon:that._iconos["START"],draggable:true});
				that._map.addOverlay(that._marcador_inicio);

				GEvent.addListener(that._marcador_inicio, "dragstart", function() {
				  that._map.closeInfoWindow();
				});

				GEvent.addListener(that._marcador_inicio, "", function(){
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});

				GEvent.addListener(that._marcador_inicio, "click", function(){
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});


				GEvent.addListener(that._marcador_inicio, "dragend", function(position) {
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
					if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(position);
				});
			}

			if (typeof(position.gearsAddress) != 'undefined') {
				var address =
					((position.gearsAddress.city)?position.gearsAddress.city:'')+' '+
					((position.gearsAddress.country)?position.gearsAddress.country:'')+' '+
					((position.gearsAddress.postalCode)?position.gearsAddress.postalCode:'');
			}
			if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(that._userLocation, address);
		},
		this._handleGearsError);
	}
	else if (typeof(this._gears)!='undefined' && this._gears){
		this._gears.getCurrentPosition(function(position){
			that._userLocation = new GLatLng(position.latitude, position.longitude);
			if (typeof(that._marcador_inicio)!='undefined'){
				that._marcador_inicio.setLatLng(that._userLocation);
			}else{
				that._marcador_inicio = new GMarker(that._userLocation, {icon:that._iconos["START"],draggable:true});
				that._map.addOverlay(that._marcador_inicio);

				GEvent.addListener(that._marcador_inicio, "dragstart", function() {
				  that._map.closeInfoWindow();
				});

				GEvent.addListener(that._marcador_inicio, "", function(){
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});

				GEvent.addListener(that._marcador_inicio, "click", function(){
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});

				GEvent.addListener(that._marcador_inicio, "dragend", function(position) {
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
					if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(position);
				});
			}

			if (typeof(position.gearsAddress) != 'undefined') {
				var address =
					((position.gearsAddress.city)?position.gearsAddress.city:'')+' '+
					((position.gearsAddress.country)?position.gearsAddress.country:'')+' '+
					((position.gearsAddress.postalCode)?position.gearsAddress.postalCode:'');
			}
			if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(position, address);
		},
		this._handleGearsError,	{enableHighAccuracy: true,gearsRequestAddress: true});
	}else if (typeof(google)!='undefined' && typeof(google.loader)!='undefined' && (typeof(google.loader.ClientLocation)!='undefined' && google.loader.ClientLocation)) {
			that._userLocation = new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
			if (typeof(that._marcador_inicio)!='undefined'){
				that._marcador_inicio.setLatLng(that._userLocation);
			}else{
				that._marcador_inicio = new GMarker(that._userLocation, {icon:that._iconos["START"],draggable:true});
				that._map.addOverlay(that._marcador_inicio);

				GEvent.addListener(that._marcador_inicio, "dragstart", function() {
				  that._map.closeInfoWindow();
				});

				GEvent.addListener(that._marcador_inicio, "", function(){
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});

				GEvent.addListener(that._marcador_inicio, "click", function(){
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
				});

				GEvent.addListener(that._marcador_inicio, "dragend", function(position) {
					that._userLocation = that._marcador_inicio.getLatLng();
					that._map.setCenter(that._userLocation);
					that._writeInfoPanel(that._marcador_inicio);
					if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(position);
				});
			}

			if (typeof(google.loader.ClientLocation.address) != 'undefined') {
				var address =
					((google.loader.ClientLocation.address.city)?google.loader.ClientLocation.address.city:'')+' '+
					((google.loader.ClientLocation.address.country)?google.loader.ClientLocation.address.country:'')+' '+
					((google.loader.ClientLocation.address.postalCode)?google.loader.ClientLocation.address.region:'');
			}
			if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(that._userLocation, address);
	}else{
//		alert('ha sido imposible crear un objeto gears para su navegador, el marcador de inicio de viaje se colocará en la posición por defecto en la puerta del Campus de Espinardo.');
	}
}

Accessia_v2_Gmap.prototype.initLocation = function(init){
	var that = this;
	if (init == null) {
		this._userLocation = new GLatLng(38.019160, -1.166390);
		this._final_location = "38.019160, -1.166390";
		this._map.setCenter(this._userLocation, this._ACCESSIA_ZOOM);
	}
	else this._userLocation = init;

	/*
	 * Una vez puesta la inicial intentamos usar gears.
	 */
	if (this._marcador_inicio != null) this._map.removeOverlay(this._marcador_inicio);

	this._marcador_inicio = new GMarker(this._userLocation, {icon:this._iconos["START"],draggable:true});

	if (init == null) this._gears_init();

	GEvent.addListener(this._marcador_inicio, "dragstart", function() {
	  that._map.closeInfoWindow();
	});

	GEvent.addListener(this._marcador_inicio, "", function(){
		that._userLocation = that._marcador_inicio.getLatLng();
		that._map.setCenter(that._userLocation);
		that._writeInfoPanel(that._marcador_inicio);
	});

	GEvent.addListener(this._marcador_inicio, "click", function(){
		that._map.setCenter(that._userLocation);
		that._writeInfoPanel(that._marcador_inicio);
	});

	GEvent.addListener(this._marcador_inicio, "dragend", function(position){
		that._marcador_inicio.setLatLng(position);
		that._userLocation = that._marcador_inicio.getLatLng();
		that._map.setCenter(that._userLocation);
		that._writeInfoPanel(that._marcador_inicio);
		if (typeof(that._onHomeDrop)!='undefined') that._onHomeDrop(position);
	});

	this._map.addOverlay(that._marcador_inicio);
}
Accessia_v2_Gmap.prototype.home_change = function(position){
	this._marcador_inicio.setLatLng(position);
	this._userLocation = this._marcador_inicio.getLatLng();
	this._map.setCenter(this._userLocation);
	this._writeInfoPanel(this._marcador_inicio);
	if (typeof(this._onHomeDrop)!='undefined') this._onHomeDrop(position);
}

Accessia_v2_Gmap.prototype.doDirections = function(callback){
	if (typeof(callback)!='undefined') this._custom_directions_handler = GEvent.addListener(this._gdir, "load", callback);
	this.searchLocation(this._userLocation.lat()+' '+this._userLocation.lng(), this._final_location,'es');
}

Accessia_v2_Gmap.prototype.infoWindowResize = function(){
	if (this._map != 'undefined' && this._map) {
		if (this._marcador_destino != 'undefined' && this._marcador_destino)
			if (!this._map.getInfoWindow().isHidden()) this._map.getTabbedMaxContent().checkResize();
	}
}

Accessia_v2_Gmap.prototype.searchLocation = function(from, to, locale){
	this._gdir.clear();
	this._gdir.load("from: "+from+" to: "+to, {"locale":locale});
}

Accessia_v2_Gmap.prototype.onGDirectionsLoad = function(){
	if (Accessia_v2_Gmap.prototype._custom_directions_handler!=null) {
		GEvent.removeListener(Accessia_v2_Gmap.prototype._custom_directios_handler);
		Accessia_v2_Gmap.prototype._custom_directions_handler = null;
	}
}

Accessia_v2_Gmap.prototype.loadGroundOverlays = function(go){
	var that = this;
	$.each(go, function(o){
		if (typeof(go[o])==='object'){
			var c = new GGroundOverlay(go[o].url, new GLatLngBounds(new GLatLng(go[o].bounds.sw.lat, go[o].bounds.sw.lng),new GLatLng(go[o].bounds.ne.lat, go[o].bounds.ne.lng)));
			that._map.addOverlay(c);
		}
	});
}

Accessia_v2_Gmap.prototype.addPlugins = function(plugins){
	var that = this;
	$.each(plugins, function(control){
		var func = ( typeof(plugins[control] === 'string') ? window[plugins[control]] : plugins[control] );
		if (typeof (func) === 'function') that._map.addControl(new func(that));
		else if (typeof(func) === 'object') that._map.addControl(func);
	});
}


/******************************   PLUGIN SECTION ***********************************/

/*
 * PLUGIN ---- CONTROL LUGARES EXTRA (cafeterias, etc...)
*/
ControlLugares = function(target){this.target = target;}
ControlLugares.prototype = new GControl();
ControlLugares.prototype.initialize = function(map){
	$(map.getContainer()).append("\
	<div id=\"myMenuDiv\" style=\"background-color:#FFF;\">\
		<div id=\"myMenuDivClicker\" style='border:1px solid #888; padding:1px; padding-left:15px; padding-right:15px; text-align:center;'>\
			<a style='text-decoration:none; color:#000; font-family:arial,sans-serif; font-weight:bold; font-size:12px;' href='#'>M&aacute;s UM</a>\
		</div>\
		<div id='myCustomController' style='display:none; background-color:#FFF; border:1px solid #888; border-top:0px; padding:5px;'>\
			<input class='check' type='checkbox' name='BIBLIOTECA'/> Bibliotecas <br>\
			<input class='check' type='checkbox' name='COMEDOR'/> Comedores Campus<br>\
			<input class='check' type='checkbox' name='CAFETERIA'/> Cafeter&iacute;as Campus<br>\
			<input class='check' type='checkbox' name='BANCO'/> Bancos <br>\
			<input class='check' type='checkbox' name='PARADABUS'/> Parada Autob&uacute;s <br>\
			<input class='check' type='checkbox' name='PARKING'/> Parking <br>\
			<input class='check' type='checkbox' name='HOTELCONVENIO'/> Hoteles Convenio<br>\
		</div>\
	</div>");
	$("#myMenuDiv").hover(
		function(){$("#myCustomController").css("display","block")},
		function(){$("#myCustomController").css("display","none")}
	);
	var target = this.target;
	$(".check").click(function(){
		if (this.checked == true) {
			target._addMarkers(this.name);
//			if (this.name == "HOTELCONVENIO") target._changeMapZoom(14, new GLatLng(37.988384,-1.124468));
//			else target._changeMapZoom(15, new GLatLng(38.016979, -1.169915));
		}
		else target._removeMarkers(this.name);
	});
	return document.getElementById("myMenuDiv");
}
ControlLugares.prototype.getDefaultPosition = function(){
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, ( ($.browser.msie) ? new GSize(200, 7) : new GSize(180, 7)) );
}



/*
 * PLUGIN ---- CONTROL LINEA TRANVIA
*/
LineaTranvia = function(target){this.target = target;};
LineaTranvia.prototype = new GControl();
LineaTranvia.prototype.initialize = function(map){
	$(map.getContainer()).append("\
	<div id='lineatranvia' class='control_nuevo' >\
		<div style='border:1px solid #888; padding:1px; padding-left:15px; padding-right:15px; text-align:center; width:100px;'>\
			<a class='lineatranviaclick' style='text-decoration:none; color:#000; font-family:arial,sans-serif; font-weight:bold; font-size:12px;' href='#'>l&iacute;nea tranv&iacute;a</a>\
		</div>\
	</div>");
	var target = this.target;
	$(".lineatranviaclick").click(function(){
		if (!target._KMLS['TRANVIA'].visible) {
			target._loadKML('TRANVIA');
			$("#lineatranvia").addClass("tranvia_highlight");
		}
		else {
			target._removeKML('TRANVIA');
			$("#lineatranvia").removeClass("tranvia_highlight");
		}
	});
	return document.getElementById("lineatranvia");
}
LineaTranvia.prototype.getDefaultPosition = function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 7));
}

/*
 * PLUGIN ---- CONTROL CARRIL BICI
*/
CarrilBici = function(target){this.target = target;};
CarrilBici.prototype = new GControl();
CarrilBici.prototype.initialize = function(map){
	$(map.getContainer()).append("\
	<div id='carrilbici' style='background-color:#FFF;' >\
		<div style='border:1px solid #888; padding:1px; padding-left:15px; padding-right:15px; text-align:center; width:100px;'>\
			<a class='carrilbiciclick' style='text-decoration:none; color:#000; font-family:arial,sans-serif; font-weight:bold; font-size:12px;' href='#'>carril bici</a>\
		</div>\
	</div>");
	var target = this.target;
	$(".carrilbiciclick").click(function(){
		if (!target._KMLS['BICI'].visible) {
			target._loadKML('BICI');
			$("#carrilbici").addClass("bici_highlight");
		}
		else {
			target._removeKML('BICI');
			$("#carrilbici").removeClass("bici_highlight");
		}
	});
	return document.getElementById("carrilbici");
}
CarrilBici.prototype.getDefaultPosition = function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 27));
}


/*
 * PLUGIN ---- CONTROL ACTUACIONES
*/
Actuaciones = function(target){this.target = target;};
Actuaciones.prototype = new GControl();
Actuaciones.prototype.initialize = function(map){
	$(map.getContainer()).append("\
	<div id='actuaciones' style='background-color:#FFF;' >\
		<div style='border:1px solid #888; padding:1px; padding-left:15px; padding-right:15px; text-align:center; width:100px;'>\
			<a class='actuacionesclick' style='text-decoration:none; color:#000; font-family:arial,sans-serif; font-weight:bold; font-size:12px;' href='#'>accesos campus</a>\
		</div>\
	</div>");
	var target = this.target;
	$(".actuacionesclick").click(function(){
		if (!target._KMLS['ACTUACIONES'].visible) {
			target._loadKML('ACTUACIONES');
			$("#actuaciones").addClass("actuacion_highlight");
		}
		else {
			target._removeKML('ACTUACIONES');
			$("#actuaciones").removeClass("actuacion_highlight");
		}
	});
	return document.getElementById("actuaciones");
}
Actuaciones.prototype.getDefaultPosition = function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 47));
}

/*
 * PLUGIN PARA AÑADIR BOTÓN DE MÁS OPCIONES CON WIKI, ETC...
*/


MoreControl = function(target) {this.target = target;};
MoreControl.prototype = new GControl();

MoreControl.prototype.layers = [
 { name: "Pano", obj: new GLayer("com.panoramio.all") },
 { name: "Tube", obj: new GLayer("com.youtube.all") },
 { name: "Wiki", obj: new GLayer("org.wikipedia.en") },
 { name: "Cams", obj: new GLayer("com.google.webcams") },
 { name: "", obj : new GStreetviewOverlay() }
];

MoreControl.prototype.hideAll = function() {
 this.boxes = document.getElementsByName("mark");
 for(var i = 0; i < this.boxes.length; i++) {
  if(this.boxes[i].checked) {
   this.boxes[i].checked = false;
   this.switchLayer(false, this.layers[i].obj);
   this.chosen.push(i);
  }
 }
}

MoreControl.prototype.checkChecked = function() {
 /* Returns true if a checkbox is still checked
 *  otherwise false
 */
 this.boxes = document.getElementsByName("mark");
 for(var i = 0; i < this.boxes.length; i++) {
  if(this.boxes[i].checked) return true;
 }
 return false;
}

MoreControl.prototype.switchLayer = function(checked, layer) {
 /* Function was originally borrowed from Esa:
 *  http://esa.ilmari.googlepages.com/dropdownmenu.htm
 */
 this.layerbox = document.getElementById("box");
 this.boxlink = document.getElementById("boxlink");
 this.button = document.getElementById("more_inner");

 if(checked) {
   this.target._map.addOverlay(layer);
   // Reset chosen array
   this.chosen.length = 0;
   /* Highlight the link and
   *  make the button font bold.
   */
   this.boxlink.className ="highlight";
   this.layerbox.className ="highlight";
   this.button.className ="highlight";
 }
 else {
   this.target._map.removeOverlay(layer);
   /*  Reset the link and the button
	* if all checkboxes were unchecked.
   */
   if(!this.checkChecked()) {
	this.boxlink.blur();
	this.boxlink.className ="";
	this.layerbox.className ="";
	this.button.className ="";
   }
 }
}

MoreControl.prototype.showLayerbox = function() {
 if(window.timer) clearTimeout(timer);
 document.getElementById("box").style.display = "block";
 this.button = document.getElementById("more_inner");
 this.button.style.borderBottomWidth = "4px";
 this.button.style.borderBottomColor = "white";
}

MoreControl.prototype.setClose = function() {
 this.layerbox = document.getElementById("box");
 this.button = document.getElementById("more_inner");

var that = this;
timer = window.setTimeout(function() {
  that.layerbox.style.display = "none";
  that.button.style.borderBottomWidth = "1px";
 }, 400);
}


MoreControl.prototype.toggleLayers = function() {
 if(this.chosen.length > 0 ) {
   /* Make an independent copy of chosen array since switchLayer()
   *  resets the chosen array, which may not be useful here.
   */
   var copy = chosen.slice();
   for(var i = 0; i < copy.length; i++) {
	var index = parseInt(copy[i]);
	this.switchLayer(true, this.layers[index].obj);
	document.getElementsByName("mark")[index].checked = true;
   }
 }
 else {
  this.hideAll();
 }
}

MoreControl.prototype.initialize = function(map) {
 var more = document.getElementById("outer_more");
 var buttonDiv = document.createElement("div");
 buttonDiv.id = "morebutton";
 buttonDiv.title = "Show/Hide Layers";
 buttonDiv.style.border = "1px solid black";
 buttonDiv.style.width = "86px";
 var textDiv = document.createElement("div");
 textDiv.id = "more_inner";
 textDiv.appendChild(document.createTextNode("Más..."));
 buttonDiv.appendChild(textDiv);
 this.chosen = new Array();

 // Register Event handlers
 more.onmouseover = this.showLayerbox;
 more.onmouseout = this.setClose;
 buttonDiv.onclick = this.toggleLayers;

 // Insert the button just after outer_more div
 more.insertBefore(buttonDiv, document.getElementById("box").parentNode);
 // Remove the whole div from its location and reinsert it to the map
 map.getContainer().appendChild(more);

 var that = this;
 $(".switchlayer_control").click(function(){ 	that.switchLayer(this.checked, that.layers[$(this).attr("rel")].obj);	});
 $(".switchlayer_hideall").click(function(){	that.hideAll();	});
 return more;
};

MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_RIGHT, ( ($.browser.msie) ? new GSize(110, 7) : new GSize(90, 7)) );
};


/*
 * 	PRUEBA PARA AÑADIR LAYERS TRANSPARENTES EN LUGAR DE LOS FIJOS Y PODER TENER EL MISMO MAPA REDIMENSIONADO PERO CON LAS CARRETERAS INFERIORES IGUALES AL MAPA NORMAL.
*/

Accessia_v2_Gmap.prototype._image_route = "http://beta2009.accessia.es/images/map_images/universidad_de_murcia_transparentes/",
Accessia_v2_Gmap.prototype._ciencias_salud = "campus_ciencias_salud/",
Accessia_v2_Gmap.prototype._ciencias_salud_nuevo = "campus_ciencias_salud_nuevo/",
Accessia_v2_Gmap.prototype._merced = "campus_merced/",
Accessia_v2_Gmap.prototype._merced_nuevo = "campus_merced_nuevo/",
Accessia_v2_Gmap.prototype._espinardo = "campus_espinardo/",
Accessia_v2_Gmap.prototype._espinardo_nuevo = "campus_espinardo_nuevo/",
Accessia_v2_Gmap.prototype._customGetTileUrl = function(a,b) {
	var f;
	switch(b) {
		case 13 : if (a.x == 4069 && a.y == 3159) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._espinardo+"Tile_"+a.x+"_"+a.y+"_"+b+".png";
					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 14 : if (a.x == 8138 && a.y == 6319) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._espinardo+"Tile_"+a.x+"_"+a.y+"_"+b+".png";

					/* DEFINICION DEL CAMPUS DE LAS CIENCIAS */
					else if ( (a.x == 8139) && (a.y == 6323) ) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._ciencias_salud+"Tile_"+a.x+"_"+a.y+"_"+b+".png";

					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		case 15 : if ( (a.x >= 16276 && a.x <= 16278 ) && (a.y >= 12635 && a.y <= 12639 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._espinardo_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					/* DEFINICION DEL CAMPUS DE LAS CIENCIAS */
					else if ( (a.x >= 16277 && a.x <= 16279 ) && (a.y >= 12646 && a.y <= 12649 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._ciencias_salud_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					/* DEFINICION DEL CAMPUS DE LA MERCED */
					else if ( (a.x >= 16280 && a.x <= 16281 ) && (a.y >= 12639 && a.y <= 12641 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._merced_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		/* Cambiado de 32552 ; 32557 a 32553 y 32558 */

		case 16 : if ( (a.x >= 32551 && a.x <= 32557 ) && (a.y >= 25272 && a.y <= 25277 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._espinardo_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					/* DEFINICION DEL CAMPUS DE LAS CIENCIAS */
					else if ( (a.x >= 32555 && a.x <= 32557 ) && (a.y >= 25293 && a.y <= 25296 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._ciencias_salud_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					/* DEFINICION DEL CAMPUS DE LA MERCED */
					else if ( (a.x >= 32562 && a.x <= 32563 ) && (a.y >= 25280 && a.y <= 25282 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._merced_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

					else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
					break;
		/* Cambiado de 65112 a 65114 */

		case 17 :
				/* DEFINICION DEL CAMPUS DE ESPINARDO */
				if ( (a.x >= 65103 && a.x <= 65112 ) && (a.y >= 50544 && a.y <= 50555 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._espinardo_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

				/* DEFINICION DEL CAMPUS DE LAS CIENCIAS */
				else if ( (a.x >= 65111 && a.x <= 65115 ) && (a.y >= 50590 && a.y <= 50593 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._ciencias_salud_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

				/* DEFINICION DEL CAMPUS DE LA MERCED */
				else if ( (a.x >= 65125 && a.x <= 65127 ) && (a.y >= 50562 && a.y <= 50565 )) f = Accessia_v2_Gmap.prototype._image_route+Accessia_v2_Gmap.prototype._merced_nuevo+"MapSnapShot_"+a.x+"_"+a.y+"_"+b+".png";

				else f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
				break;
		default:  f = G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
	}
	return f;
}
Accessia_v2_Gmap.prototype.tileLayers = [(G_NORMAL_MAP.getTileLayers())[0], new GTileLayer(this.copyRight , 1, 17, {isPng : true})];
Accessia_v2_Gmap.prototype.init_layers = function(map){
	this.tileLayers[1].getTileUrl = this._customGetTileUrl;
	var custommap = new GMapType(this.tileLayers, G_SATELLITE_MAP.getProjection(), "Callejero", {errorMessage:"No data available"});	
	((map != 'undefined')?map:this._map).addMapType(custommap);
	((map != 'undefined')?map:this._map).setMapType(custommap);
}


/**
 *	USANDO LOS CLUSTERS
*/
/*
 * Quizás deberíamos añadir "_clusters" y las variables de clusters y marcadores espciales en este punto...
 */
Accessia_v2_Gmap.prototype._clusterStyles = {
		"BIBLIOTECA" : [{
				url: '/images/clusterBiblioteca_30.png',
				height: 29,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterBiblioteca_40.png',
				height: 39,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterBiblioteca_50.png',
				height: 40,
				width: 50
			}],
		"COMEDOR" : [{
				url: '/images/clusterComedor_30.png',
				height: 29,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterComedor_40.png',
				height: 38,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterComedor_50.png',
				height: 47,
				width: 50
			}],
		"CAFETERIA" : [{
				url: '/images/clusterCafeteria_30.png',
				height: 32,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterCafeteria_40.png',
				height: 42,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterCafeteria_50.png',
				height: 52,
				width: 50
			}],
		"BANCO" : [{
				url: '/images/clusterBanco_30.png',
				height: 29,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterBanco_40.png',
				height: 39,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterBanco_50.png',
				height: 49,
				width: 50
			}],
		"PARADABUS" : [{
				url: '/images/clusterParadabus_30.png',
				height: 29,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterParadabus_40.png',
				height: 38,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterParadabus_50.png',
				height: 48,
				width: 50
			}],
		"HOTELCONVENIO" : [{
				url: '/images/clusterHotel_30.png',
				height: 29,
				width: 30,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterHotel_40.png',
				height: 38,
				width: 40,
				opt_textColor: '#FFFFFF'
			},
			{
				url: '/images/clusterHotel_50.png',
				height: 48,
				width: 50
			}],
		"PARKING" : [{
				url: '/images/clusterParking_30.png',
				height: 28,
				width: 30,
				opt_textColor: '#FF0000'
			},
			{
				url: '/images/clusterParking_40.png',
				height: 37,
				width: 40,
				opt_textColor: '#FF0000'
			},
			{
				url: '/images/clusterParking_50.png',
				height: 46,
				width: 50
			}]
	}
Accessia_v2_Gmap.prototype._addMarkers = function(tipo){
	if (tipo == null || tipo === 'undefined' || typeof tipo === 'undefined') return false;
	else if (typeof(this._conjuntos[tipo]) === 'undefined') return false;
	if (this._conjuntos[tipo].length == 0) this._loadMarkers(tipo);
	//for(i = 0; i < this._conjuntos[tipo].length; i++) this._map.addOverlay(this._conjuntos[tipo][i]);
		/* USANDO	MARKERCLUSTER */
	this._clusters[tipo] = new MarkerClusterer(this._map, this._conjuntos[tipo], {maxZoom : this._clustersMaxZoom, gridSize : this._clustersGridSize, styles : this._clusterStyles[tipo] });
}
Accessia_v2_Gmap.prototype._removeMarkers = function(tipo) {
	if (tipo == null || tipo === 'undefined' || typeof tipo === 'undefined') return false;
	else if (typeof(this._conjuntos[tipo]) === 'undefined') return false;
	//for(i = 0; i < this._conjuntos[tipo].length; i++) this._map.removeOverlay( this._conjuntos[tipo][i] );
		/* USANDO 	MARKERCLUSTER*/
	if (typeof(this._clusters[tipo]) != 'undefined' && this._clusters[tipo] && this._clusters[tipo].getTotalMarkers != 0) this._clusters[tipo].clearMarkers();
}



/*
 * PRUEBAS PARA AÑADIR LOS FIXEDMARKERS COMO PARTE EXTRA DEL API
*/
/*
 * FIXED TABBED MARKER TIENE LA MISMA FUNCIONALIDAD QUE TABBEDMARKER, pero sin eventos asociados
*/
Accessia_v2_Gmap.prototype._createFixedTabbedMarker = function(latlng, id, min, sum, tabs, taboptions, markeroptions, parking, type){
	  var _marker = new GMarker(latlng, ((markeroptions)?markeroptions:{}));
	  _marker.min = min;
	  _marker.overlay = null;
	  _marker.sum = sum;
	  _marker.id = id;
	  _marker.tabs = tabs;
	  _marker.taboptions = taboptions;

	  var that = this;

	  GEvent.addListener(_marker, 'click', function(){
		if (!that._last_marker_is_fixed && typeof(that._marcador_destino) && that._marcador_destino) {
			that._map.removeOverlay(that._marcador_destino);
		}
		that._marcador_destino = _marker;
		that._last_marker_is_fixed = true;
		that._final_location = ((typeof (parking.lat())!='undefined')?parking.lat():latlng.lat) + " " + ((typeof (parking.lng()) !='undefined')?parking.lng():latlng.lng);
		if (that._maximizeEndHandler) GEvent.removeListener(that._maximizeEndHandler);
		that._maximizeEndHandler = GEvent.addListener(that._map.getInfoWindow(), "maximizeend", that._maximizeEnd[type]);
		/* Añadimos más efecto al cerrar el marcador */
		if (that._maximizeCloseClickHandler) GEvent.removeListener(that._maximizeCloseClickHandler);
		that._maximizeCloseClickHandler = GEvent.addListener(that._map.getInfoWindow(), "closeclick", function(){
			that._map.getInfoWindow().hide();
			that._map.panTo(that._marcador_destino.getLatLng());
		});
		if (that._openInfoWindowHandler) GEvent.removeListener(that._openInfoWindowHandler);
		that._openInfoWindoHandler = GEvent.addListener(that._map, 'infowindowopen', function(){
			$('#_link_searchlocation').unbind('click').click(function(){
				that.searchLocation(that._userLocation.lat()+' '+that._userLocation.lng(), that._final_location,'es');return false;
			});
		});
		_marker.openMaxContentTabsHtml(that._map, _marker.min, _marker.sum, _marker.tabs, _marker.taboptions);
	  });

	  _marker.resize = $(window).resize(function(){
		that._map.getTabbedMaxContent().checkResize();
	  });

	  return _marker;
};

/*
  * @markers {Array} Cada marker puede traer consigo una serie de parámetros específicos.
  * @markers.tabs {Array} Array donde cada elemento es un objeto con "title" y "content"
  * @markers.myIconUrl {String} String que puede estar definida o no donde se indica la URL de la imagen que usará dicho marcador
  * @callbacks {object} Atributo - Valor, donde atributo es el evento y valor la función asociada al evento.
*/
Accessia_v2_Gmap.prototype.fixedMarkers = Array();
Accessia_v2_Gmap.prototype.addFixedMarkers = function(markers, callbacks){
	var that  = this;
	$.each(markers, function(index){
		var position = markers[index];
		if (typeof(position)!='object') return false;

		var _id = position.place+'_'+Math.floor(Math.random()*10001)+'_'+((new Date()).getTime());
		var _icon = null;
		var infoString = "<br>Se ha establecido:<br>"+
		 "<b>"+position.name+"</b><br>Como lugar de destino<br>"+
		 "<br><a href='#' id='_link_searchlocation' class='no_blank_' >Calcular ruta...</a>";
		infoString += "<p>&nbsp;</p>";
		var full_infoString = infoString;
		var planosPlanta = new Array();
		var tabs = new Array();

		if (typeof(position.description) != 'undefined') infoString += position.description;
		tabs.push(new MaxContentTab("Informaci&oacute;n", '<div class="'+that._blank_links_class+'">'+infoString+'</div>'));
		if (typeof(position.plantas) != 'undefined' ) {
			try {
				var plantas = eval(position.plantas);
				if (plantas.length>0){
					var htmlPlantas = "<ul>";
					for (i=0; i<plantas.length; i++){
						htmlPlantas+="<li><a href='"+that._planos_base+plantas[i].value+"' rel='lightbox' class='effectable' title='"+plantas[i].name+"'>"+plantas[i].name+"</a></li>";
					}
					htmlPlantas += "</ul>";
					tabs.push(new MaxContentTab("Plano", htmlPlantas));
				}
			}
			catch(e){}
		}
		if (typeof(position.tabs)!='undefined'){
			for (var i = 0; i < e.tabs.length; i++) {
				tabs.push(new MaxContentTab(e.tabs[i].title, '<div class="'+that._blank_links_class+'">'+e.tabs[i].content+'</div>'));
			}
		}
		if (typeof(position.myIconUrl)!='undefined'){
			if (position.myIconUrl != ""){
				_icon = new GIcon(that._littleIcon, position.myIconUrl);
			}
		}

		var parking = new GLatLng(position.lat_parking, position.lng_parking);
		var taboptions = {
			maximized : false,
			maxTitle: position.name, 			/* he cambiado simpleContent por name */
			selectedTab : 0
		}

		var marker = that._createFixedTabbedMarker(
			new GLatLng( position.lat, position.lng ),
			_id,
			infoString,
			'',
			tabs,
			taboptions,{
				icon : _icon,
				draggable : false,
				title : position.name
			},
			parking,
			position.type
		);

		if (typeof(callbacks!='undefined')) {
			$.each(callbacks, function(i, o){
				GEvent.addListener(marker, i, o);
			});
		}

		that.fixedMarkers.push(marker);
		that._map.addOverlay(that.fixedMarkers[that.fixedMarkers.length-1]);
	});
}


/*
 * FIXED MARKERS HIDE ON ZOOM ADDON
*/
Accessia_v2_Gmap.prototype.fixed_markers_max_zoom = 14;
Accessia_v2_Gmap.prototype.fixed_markers_hide_handler = null;
Accessia_v2_Gmap.prototype.fixed_markers_are_hidden = false;
Accessia_v2_Gmap.prototype.active_hide_fixed_markers = function(zoom){
	if (typeof(zoom)!='undefined') this.fixed_markers_max_zoom = zoom;
	var that = this;
	this.fixed_markers_hide_handlers = GEvent.addListener(this._map, 'zoomend', function(ol, nl){
		if (typeof(that.fixedMarkers)!='undefined'){
			if (nl <= that.fixed_markers_max_zoom && !that.fixed_markers_are_hidden) {
				$.each(that.fixedMarkers, function(index){
					if(typeof(that.fixedMarkers[index])!='function' && !that.fixedMarkers[index].isHidden()) that.fixedMarkers[index].hide();
				});
				that.fixed_markers_are_hidden = true;
			}
			else if(nl > that.fixed_markers_max_zoom && that.fixed_markers_are_hidden) {
				$.each(that.fixedMarkers, function(index){
					if( typeof(that.fixedMarkers[index])==='object' && that.fixedMarkers[index].isHidden()) that.fixedMarkers[index].show();
				});
				that.fixed_markers_are_hidden = false;
			}
		}
	});
}

Accessia_v2_Gmap.prototype.clearDirections = function(){
	if (typeof(this._gdir) != 'undefined' && this._gdir) {
		this._gdir.clear();
	}
}


/*
 * STREETVIEW DOLL ADDON
 */
/*
 * PLUGIN ---- CONTROL ACTUACIONES
*/
StreetDoll = function(target){this.target = target;}
StreetDoll.prototype = new GControl();
StreetDoll.prototype._handleError = function(error){

}
StreetDoll.prototype._dollIcon = new GIcon(G_DEFAULT_ICON, '/images/dollMarker.gif');
StreetDoll.prototype.initialize = function(map){
	var that = this;
	this._doll_marker = null;
	this._streetclient = new GStreetviewClient();
	this._errorListener = null;
	this.streetViewOverlay = new GStreetviewOverlay();
	/* definir aquí los tamaños iniciales del icono seleccionado para poder moverlo bien y usar una posición correcta al hacer drop */
	this.initial_icon_position = {
		t : 214+12,
		l : 30-2,
		w : 13,		//debe coincidir con el tamaño de la imagen
		h : 27		//debe coincidir con el tamaño de la imagen
	}
	this.target._streetDoll = this;
	$(map.getContainer()).append('\
		<div id="street_doll_control" style="background: url(\'/images/3dcontrolbutton_bottom_2.gif\') no-repeat; width:20px; height:52px; text-align:center; cursor:pointer;">\
			<image id="street_doll_icon" src="/images/dollMarker.gif" style="width:13px; height:27px; margin-top:12px; margin-left:-2px;"/>\
		</div>\
	');
	$('#street_doll_control').hover(function(){
		$('#street_doll_icon').css({'margin-top':'15px', 'margin-left':'5px'});
	},function(){
		$('#street_doll_icon').css({'margin-top':'12px', 'margin-left':'-2px'});
	});
	$('#street_doll_icon').draggable({
		appendTo : 'parent',
		revert : true,
		revertDuration : 300,
		start : function(){	map.addOverlay(that.streetViewOverlay); },
		drag : function(){},
		stop : function(e, o){
			map.removeOverlay(that.streetViewOverlay);
			var pixel = {
				left : o.position.left + that.initial_icon_position.l + that.initial_icon_position.w,
				top : o.position.top + that.initial_icon_position.t + that.initial_icon_position.h
			}
			var latlng = map.fromContainerPixelToLatLng(new GPoint(pixel.left, pixel.top));
			that.goToStreet(latlng);
		}
	});

	return document.getElementById("street_doll_control");
}
StreetDoll.prototype.goToStreet = function(latlng){
	var that = this;
	if (typeof(that._doll_marker)!='undefined' && that._doll_marker) that.target._map.removeOverlay(that._doll_marker);
	that._doll_marker = new GMarker(latlng, {icon : that._dollIcon});
	that.target._map.addOverlay(that._doll_marker);
	if (typeof(that._errorListener)!='undefined' && that._errorListener) GEvent.removeListener(that._errorListener);
	that._errorListener = GEvent.addListener(that._streetclient, 'error', that._handleError);
	that._streetclient.getNearestPanorama(latlng, function(o){
		if (o.code == 200){
			var address = (typeof(o.location.description)!='undefined')?o.location.description:''+' '+(typeof(o.location.country)!='undefined')?o.location.country:'';
			GEvent.addListener(that._doll_marker, 'click', function(){
				that._doll_marker.openInfoWindowHtml('<div><p>'+address+'</p><p><a class="_street_doll_home" href="#">Usar como inicio</a></p></div>');
			});
			if (typeof(that._doll_marker._openWindowHandler)!='undefined') GEvent.removeListener(that._doll_marker._openWindowHandler);
			that._doll_marker._openWindowHandler = GEvent.addListener(that._doll_marker, 'infowindowopen',function(){
				$("._street_doll_home").unbind('click').click(function(){
					that.target.initLocation(that._doll_marker.getLatLng());
					that.target._map.closeInfoWindow();
					map.removeOverlay(that._doll_marker);
				});
			});
			GEvent.trigger(that._doll_marker, 'click');
			if (typeof(that.target._street_doll_drop)!='undefined') that.target._street_doll_drop(o.location.latlng, o.location.pov, address);
		}else{
			GEvent.addListener(that._doll_marker, 'click', function(){
				that._doll_marker.openInfoWindowHtml('<div><p>No nos ha sido posible tomar un punto de referencia para Streetview en este punto.</p><p>Posibles soluciones:<ul><li>* Usar un nivel de zoom más próximo a la carretera</li><li>* Pulsar sobre una zona que tenga StreetView disponible</li></ul></p></div>');
			});
			GEvent.trigger(that._doll_marker, 'click');
			//alert('No se ha podido ajustar la posición de la calle o no existe vista de calle para esa localización');
		}
	});
}
StreetDoll.prototype.getDefaultPosition = function(){
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(30, 214));
}




/*
 * CONTEXT_MENU_MANAGER ADDON
 */
/**
 * @class ContextMenuManager
 * @param {Object} target
 * @description Basado en el controlador existente en los ejemplos de googlemaps.
 */
ContextMenuManager = function(target){this._target = target; this._target._contextMenu = this;}
ContextMenuManager.prototype = new GControl();
ContextMenuManager.prototype.initialize = function(map){
	this._domIDprefix = Math.floor(Math.random()*1001);
	this._map_container = map.getContainer();
	this._context_menu = document.createElement("ul");
	this._context_menu.style.font = "small Arial";
	this._context_menu.style.whiteSpace = "nowrap";
	this._context_menu.style.color = "#0000cd";
	this._context_menu.style.backgroundColor = "#fff";
	this._context_menu.style.listStyle = "none";
	this._context_menu.style.padding = "0px";
	//this._context_menu.style.width = "21ex";
	this._context_menu.style.border = "1px solid #666";
	this._context_menu.style.visibility = 'hidden';
	this._context_menu.style.display = "none";
	this._context_menu.style.padding = "5px";
	this._context_menu.visible = false;
	this._context_xy = null;
	this._context_latlng = null;

	var that = this;
	 // Prevents the browser's own context menu to appear.
	if (this._map_container.addEventListener) {
		this._map_container.addEventListener("contextmenu", function (e) {
			e.stopPropagation();
			e.preventDefault();
		}, false);
	} else if (this._map_container.attachEvent) {
		this._map_container.attachEvent("oncontextmenu", function () {
			var e = window.event;
			e.cancelBubble = true;
			e.returnValue = false;
		});
	}

	this._map_container.appendChild(this._context_menu);

	GEvent.addListener(map, 'singlerightclick', function(pixelPoint, src, ov){
		that._context_xy = pixelPoint;
 		that._context_latlng = map.fromContainerPixelToLatLng(pixelPoint);
		// Correction of IE bug
		var posX = document.all ? (pixelPoint.x - 40) : pixelPoint.x;
		var posY = document.all ? (pixelPoint.y + 10) : pixelPoint.y;

		var mapwidth = that._target._map.getSize().width;
		var mapheight = that._target._map.getSize().height;
		var menuwidth = that._context_menu.offsetWidth;
		var menuheight = that._context_menu.offsetHeight;

		// Adjusts the position of the context menu
		if (mapwidth - menuwidth < posX) {
			posX = posX - menuwidth;
		}
		if (mapheight - menuheight < posY) {
			posY = posY - menuheight - 20;
		}
		that._context_menu.style.display = "block";
		that._context_menu.style.visibility = "visible";
		that._context_menu.visible = true;
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(posX, posY));
		pos.apply(that._context_menu);
	});

	 // Closes context menu when the cursor is being moved out of the map.
	 // This DomListener is a workaround for Internet Explorer because
	 // the 'normal' GEvent Listener doesn't work correctly in IE.
	 GEvent.addDomListener(this._map_container, "mouseout", function (e) {
		 if (that._context_menu.visible) {
			 if (!e) {
			 	var e = window.event;
			 }
			 if (that.checkMouseLeave_(that._map_container, e)) {
				that._context_menu.style.visibility = 'hidden';
				that._context_menu.style.display = "none";
				that._context_menu.visible = false;
			 }
		 }
	 });

	 // Closes context menu in case of a left click on the map
	 GEvent.addListener(map, "click", function () {
		that._context_menu.style.visibility = 'hidden';
		that._context_menu.style.display = "none";
		that._context_menu.visible = false;
	 });

	 // Closes context menu after dragging the map
	 GEvent.addListener(map, "dragstart", function () {
		that._context_menu.style.visibility = 'hidden';
		that._context_menu.style.display = "none";
		that._context_menu.visible = false;
	 });

	return this._context_menu;
}
ContextMenuManager.prototype.checkMouseLeave_ = function (element, evt) {
	if (element.contains && evt.toElement) {
		return !element.contains(evt.toElement);
	} else if (evt.relatedTarget) {
		return !this.containsDOM_(element, evt.relatedTarget);
	}
}
ContextMenuManager.prototype.containsDOM_ = function (container, containee) {
	var isParent = false;
	do {
		if ((isParent = container == containee)) {
			break;
		}
		containee = containee.parentNode;
	} while(containee != null);
	return isParent;
}
ContextMenuManager.prototype.createRuler_ = function () {
	var hr = document.createElement("hr");
	hr.style.height = "1px";
	hr.style.border = "1px";
	hr.style.color = "#e2e2e2";
	hr.style.backgroundColor = "#e2e2e2";
	// Further IE bug
	if (document.all) {
		hr.style.display = "block";
		hr.style.margin = "-6px";
	} else {
		hr.style.margin = "0px";
	}
	return hr;
}
/**
 *
 * @param {Object} DOM_or_text	Objeto que será utilizado como nuevo elemento del menú, puede ser un objeto creado desde document o puede ser un string indicando el valor del campo.
 * @param {Object} callbacks	Objeto de funciones de callback para comportamientos personalizados del primer parámetro.
 *
 * @DOM_or_text [structure]
 * 		Object | String | Array
 * 	*Array Case [structure] [{object},
 * 		{
 			[{object} | {string}] element
 			{array} callbacks
 * 		}
 * 	}]
 *
 * @callbacks [structure]{
 * 	[{object},
 * 		{
 * 			{string} event			String que defnie el evento que se va a aplicar.
 * 			{function} callback		Función que realiza el comportamiento para dicho evento.
 * 			{boolean} toContainer	Si es TRUE se aplica al contenedor del objeto pasado como parámetro.
 * 			{string} ids_classes	Serie de ids y clases sobre las que se aplicará el callback para el evento en caso de que toContainer sea FALSE. En caso de ser nulo o no existir en la definición del objeto se aplicará directamente al objeto generado.
 * 									* Sintaxis :: "#id1, #id2, .clase1, .clase2"
 * 		}
 * 	]
 * }
 */
ContextMenuManager.prototype._addMenuElement = function(DOM_or_text, callbacks){
	if (typeof(DOM_or_text) === 'undefined') return false;
	var newObject = null;
	if (DOM_or_text != 'CREATE_RULER') {
		newObject = document.createElement("li");
		newObject.style.cursor = "pointer";
		switch (typeof(DOM_or_text)) {
			case 'object': newObject.appendChild(DOM_or_text); break;
			case 'string': newObject.appendChild(document.createTextNode(DOM_or_text));	break;
			default:return false;
		}
		if (typeof(callbacks) != 'undefined')
			$.each(callbacks, function(i, o){
				if ((typeof(o.toContainer) != 'undefined' && o.toContainer) ||
				((typeof(o.toContainer) === 'undefined' || !o.toContainer) && (typeof(o.ids_classes) === 'undefined' || !o.ids_classes))) {
					$(newObject).unbind(o.event).bind(o.event, o.callback);
				}
				else {
					$(o.ids_classes, newObject).unbind(o.event).bind(o.event, o.callback);
				}
			});
	}else newObject = this.createRuler_();
	var wasVisible = this._context_menu.visible;
	this._context_menu.appendChild(newObject);
	if (!wasVisible) {
		this._context_menu.style.visibility = 'hidden';
		this._context_menu.visible = false;
	}
}
ContextMenuManager.prototype.addMenuElement = function(DOM_or_text, callbacks){
	var that = this;
	if (DOM_or_text instanceof Array) $.each(DOM_or_text, function(i,o) {that._addMenuElement(o.element, o.callbacks);});
	else this._addMenuElement(DOM_or_text, callbacks);
}



/**
 * Para imprimir desde google usando el proxy de accessia.
 * @param {Object} obj
 * 		@template {Object} : [
 * 			@member {String} from : Define desde donde vamos, puede ser una dirección completa o un par "lat,lng" sin espacios
 * 			@member {String} to : Define a donde vamos, puede ser una dirección completa o un par "lat,lng" sin espacios
 * 			@member {Number} zoom : Define el nivel de zomo que queremos que tenga el mapa grande en la impresión
 * 			@member {Boolean} from_is_latlng : indica que from es un par lat,lng sin espacios
 * 			@member {Boolean} to_is_latlng : indica que to es un par "lat,lng" sin espacios
 * 		]
 *
 * Ninguno de los parámetros es requerido a excepción de los booleanos si existe [from|to] y es "lat,lng"
 */
Accessia_v2_Gmap.prototype.printWithGoogle = function(obj){
	if (typeof(this._gdir)!='undefined' && this._gdir){
		if (this._gdir.getNumGeocodes()>1){
			var from = "";
			var to = "";
			var zoom = "";
			//Ver si está el from
			if (typeof(obj.from)==='undefined' || !obj.from){
				from = this._gdir.getGeocode(0).Point.coordinates[1] + ',' + this._gdir.getGeocode(0).Point.coordinates[0];
			}else if (typeof(obj.from_is_latlng) != 'undefined' && obj.from_is_latlng){
				from = obj.from;
			}else{
				from = obj.from;
				from = from.replace(/ /g, '+');
				from = from.replace(/,/g, '');
				from = escape(from);
			}
			//Ver si está el to
			if (typeof(obj.to)==='undefined' || !obj.to){
				to = this._gdir.getGeocode(1).Point.coordinates[1] + ',' + this._gdir.getGeocode(1).Point.coordinates[0];
			}else if (typeof(obj.to_is_latlng) != 'undefined' && obj.to_is_latlng){
				to = obj.to;
			}else{
				to = obj.to;
				to = to.replace(/ /g, '+');
				to = to.replace(/,/g, '');
				from = escape(to);
			}

			//Ver si el zoom está o no definido.
			if (typeof(obj.zoom)==='undefined' || !obj.zoom) zoom = ""; else zoom = obj.zoom;

			var url = this._google_print+'?from='+from+'&to='+to+'&zoom='+zoom;
			return url;
		}
	}
}

