
//<![CDATA[

// Ponemos en marcha on load window el script principal

AttachEvent(window,"load",accionarMapa);

AttachEvent(window,"load",recogerIdURL);

//==========================================
//
// Funciones para el mapa
//
//==========================================

var map;
var id_mapa = "mapa-cit";
var center;
var center_lat = 28.414126;
var center_lng = -16.542878;

var center_zoom = 15;
var marcador;

function accionarMapa() {

	if (document.getElementById(id_mapa)) {

		if (GBrowserIsCompatible()) {
		
			// Creamos el GIcon por defecto
			var icon = new GIcon();
			icon.image = "http://www.google.com/mapfiles/marker.png";
			icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
			icon.iconSize = new GSize(20, 34);
			icon.shadowSize = new GSize(37, 34);
			icon.iconAnchor = new GPoint(10, 34);

			document.getElementById(id_mapa).style.display = "block";

			// Creamos el GMap
			map = new GMap2(document.getElementById(id_mapa));
			
			// Aplicamos la nueva interfaz de control de mapas 
		
			map.setUIToDefault();
			
			// Permitimos zoom con el scroll
			//map.enableScrollWheelZoom();
			
			// Añadimos los controles deseados
			
				// Al aplicar la nueva interfaz de mapas no podemos asignar la antigua interfaz
				//map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());

			// Centramos el mapa
			center = new GLatLng(center_lat, center_lng);
			map.setCenter(center, center_zoom);

			//map.setMapType(G_HYBRID_MAP); // <-------------------------------------------------------------- Activar
			
			
			if (document.getElementById("latitud")) {

			// Si existe un elemento con id latitud estamos ante:
			//
			// a) un mapa de localización de un elemento
			// b) un mapa de inclusión de coordenadas
			
				// Tomamos el campo latitud como referencia
				
				campo_latitud = document.getElementById("latitud").value;
			
				if (document.getElementById("coordenadas-estaticas") && document.getElementById("coordenadas-estaticas").value == "true") {
				
				// a) Estamos ante un mapa de localización de un elemento
				
					// Tomamos lat y lng y creamos el marcador
				
					latitud = parseFloat(document.getElementById("latitud").value);
					longitud = parseFloat(document.getElementById("longitud").value);
					var marcador = new GMarker(new GLatLng(latitud, longitud), {draggable: false});
					
					// Colocamos el marcador
					
					map.addOverlay(marcador);
				
				} else {
				
				// b) Estamos ante un mapa de inclusión de coordenadas



					if (campo_latitud == "") {

						var marcador = new GMarker(center, {draggable: true});

					} else {

						latitud = parseFloat(document.getElementById("latitud").value);
						longitud = parseFloat(document.getElementById("longitud").value);
						var marcador = new GMarker(new GLatLng(latitud, longitud), {draggable: true});

					}
					
					// Colocamos el marcador
					
					map.addOverlay(marcador);
					
					

					GEvent.addListener(marcador, "dragstart", function() {
					  map.closeInfoWindow();
					});

					GEvent.addListener(marcador, "dragend", function() {
					  //marker.openInfoWindowHtml("Mensaje...");

					  coordenadas = marcador.getPoint();

					  document.getElementById("latitud").value = coordenadas.lat();

					  document.getElementById("longitud").value = coordenadas.lng();

					});

					GEvent.addListener(map, "click", function(marker, point) {
					  if (marker) {

						marcador.hide();

					  } else {

						if (marcador.isHidden()) {

							marcador.show();

						}	

						marcador.setPoint(point);

						coordenadas = marcador.getPoint();

						document.getElementById("latitud").value = coordenadas.lat();

						document.getElementById("longitud").value = coordenadas.lng();

					  }
					});
					
					
				} // end if

			
			}
			
			// Si existe el elemento con id select-categorias estamos ante un mapa con búsqueda incorporada
			
			if (document.getElementById("select-categorias")) {
			
				// No hacemos nada especial
			
			}

		}

	} 

}	
	
// -----------------------------------------------------------------------------------------------
// Funcion recogerIdURL
//
// Recoge la id de la URL. Basada en una función de Bruno Suárez Laffargue
// -----------------------------------------------------------------------------------------------

function recogerIdURL() {

	//Definimos las variables necesarias
	id = 0;

	//Capturamos la URL
	var callingURL = document.URL;

	//Separamos los parametros
	var cgiString = callingURL.substring(callingURL.indexOf('?')+1,callingURL.length);

	//Fijamos el sepador entre parametros
	var DELIMETER = '&';

	//Eliminamos la almohadilla, si es que existe... cortamos por lo sano!
	if (cgiString.indexOf('#')!=-1){
		cgiString=cgiString.slice(0,cgiString.indexOf('#'));
	}

	//Troceamos el cgiString ya limpiado, separando cada par variable=valor
	//en una de las posiciones del array
	var arrayParams=cgiString.split(DELIMETER);

	//Recorremos el array de parametros evaluando cada uno de los pares variable=valor
	for (var i=0;i<arrayParams.length;i++){
		eval(arrayParams[i].substring(0,arrayParams[i].indexOf('=')+1)+"\""+
		arrayParams[i].substring(arrayParams[i].indexOf('=')+1,arrayParams
		 [i].length)+"\"");
	} 
	
	if (id != 0) {
	
		// Solicitamos el XML con la información del elemento cuya id hemos obtenido
	
		idXML(id);
	
	}
	
}



// **************************************************************

// -----------------------------------------------------------------------------------------------
// Funcion cambioCategoria
//
// Muestra/oculta los select de subcategorías en función de la categoría seleccionada
// -----------------------------------------------------------------------------------------------

function cambioCategoria(elemento) {

	nombre_categoria = elemento.id;
	
	subcategoria = elemento.value;

	p_subcategorias = document.getElementById(nombre_categoria + "-subcategorias");
	
	if (subcategoria > 0) {
	
		p_subcategorias.style.display = "block";

		selects = document.getElementsByTagName("select");
		
		for(var no=0;no<selects.length;no++) {
		
			if (selects[no].className == "select-subcategoria" && selects[no].parentNode.id == p_subcategorias.id) {
			
				selects[no].style.display = "none";
			
			}
		
		}

		select_subcategoria = document.getElementById(nombre_categoria + "-sub-" + subcategoria);
		
		select_subcategoria.style.display = "block";
	
	} else {
	
		p_subcategorias.style.display = "none";
	
	}

}

// -----------------------------------------------
// Funcion listadoXML
// -----------------------------------------------


function listadoXML(formulario) {

	// Ocultamos posible mensaje anterior
	
	document.getElementById("hay-resultados-busqueda-mapa").style.display = "none";
	document.getElementById("no-hay-resultados-busqueda-mapa").style.display = "none";

	// Mostramos mensaje "buscando"

	document.getElementById("buscando-busqueda-mapa").style.display = "block";

	//

	id_sector = formulario.id_sector.value;
	id_categoria = formulario.categoria.value;
	
	if (id_categoria > 0) {
	
		id_subcategoria = eval("formulario.sub_" + id_categoria +  ".value;");
	
	} else {
	
		id_subcategoria = 0;
	
	}
	
	id_zona = formulario.zona.value;	
	idioma = formulario.idioma.value;
	
	url_xml = "../../../stanquecms/modulos/empresas/xml.asp?accion=listado&idioma=" + idioma + "&sector=" + id_sector + "&categoria=" + id_categoria + "&subcategoria=" + id_subcategoria + "&zona=" + id_zona;

//	url_xml = "empresas.xml";

	importXML(url_xml, "cargarEnMapa", false, 2000);

}

// -----------------------------------------------
// Funcion idXML
// -----------------------------------------------

function idXML(id_empresa) {

	idioma = "es"; // <---------------------------------------------------------------------------------------------------------------- ELIMINAR !!!!!!!!!!!!!!!!!!!!

	url_xml = "../../../stanquecms/modulos/empresas/xml.asp?accion=localizacion&idioma=" + idioma + "&id=" + id_empresa;


//	url_xml = "empresas.xml";

	importXML(url_xml, "cargarEnMapa", false, 2000);
	
}

// -----------------------------------------------
// Funcion hayResultados
// -----------------------------------------------

function hayResultados(numero_de_resultados) {

	// Ocultamos mensaje "buscando"

	document.getElementById("buscando-busqueda-mapa").style.display = "none";
	
	// Ocultamos posible mensaje anterior
	
	document.getElementById("hay-resultados-busqueda-mapa").style.display = "none";
	document.getElementById("no-hay-resultados-busqueda-mapa").style.display = "none";

	// No hay

	if (numero_de_resultados <= 0) {
	
		// Mostramos mensaje de error
		
		document.getElementById("no-hay-resultados-busqueda-mapa").style.display = "block";
	
	} else {

		// Mostramos mensaje y número de resultados

		if (numero_de_resultados == 1) {
		
			document.getElementById("numero-resultados-busqueda").innerHTML = "un resultado";
		
		} else {
			
			document.getElementById("numero-resultados-busqueda").innerHTML = numero_de_resultados + " resultados";
		
		}

		document.getElementById("hay-resultados-busqueda-mapa").style.display = "block";

	}
	
}


// ----------------------------------------------------------------
// Funcion AttachEvent
//	Para agregar en IE y otros navegadores un evento a un elemento
// ----------------------------------------------------------------

function AttachEvent(elementObj, eventName, eventHandlerFunctionName)
{
  if (elementObj.addEventListener)
  { // Non-IE browsers
    elementObj.addEventListener(eventName, eventHandlerFunctionName, false);
  }
  else if (elementObj.attachEvent)
  { // IE 6+
   elementObj.attachEvent('on' + eventName, eventHandlerFunctionName);
  }
  else
  { // Older browsers
    var currentEventHandler = elementObj['on' + eventName];
    if (currentEventHandler == null)
    {
      elementObj['on' + eventName] = eventHandlerFunctionName;
    }
    else
    {
      elementObj['on' + eventName] = function(e) { currentEventHandler(e); eventHandlerFunctionName(e); }
    }
  }
}

//]]>
