// xml_mapa.js - 0.9.1 // 17-10-2008
//
// Este JavaScript ha sido desarrollado por Julio Loayza para stanque.com.
// 
// Utiliza: Script to import XML data files and make them available to JavaScript v2.0.6 written by Mark Wilton-Jones, 13/04/2004
//
// JavaScript bajo licencia by-nc-sa 3.0 - http://creativecommons.org/licenses/by-nc-sa/3.0/deed.es_CL
// JavaScript released under Creative Commons License - http://creativecommons.org/licenses/by-nc-sa/3.0/deed.es_CL

var markerGroups = { "alojamiento": [], "ocio": [], "gastronomia": [], "comercio": [], "servicios": [] };

var markerGroupsTemp = { "alojamiento": [], "ocio": [], "gastronomia": [], "comercio": [], "servicios": [] };

var markerGroupsFlags = { "alojamiento": false, "ocio": false, "gastronomia": false, "comercio": false, "servicios": false };

function cargarEnMapa(xmlDoc) {

	// Reinicializamos la banderas de nuevos datos para cada sector

	for (var sector in markerGroupsFlags) {
    	markerGroupsFlags[sector] = false;
    }

	if( xmlDoc.documentElement && xmlDoc.documentElement.tagName && xmlDoc.documentElement.tagName.toUpperCase() == 'HTML' ) {
		// For no apparent reason, your browser has turned the clean XML into HTML based garbage.Script aborted.
		//setTimeout('alert(\'Ha ocurrido un error al cargar la información. Por favor inténtelo de nuevo.');',50); return; 
		}

	var x = xmlDoc.getElementsByTagName("empresa");
	
	hayResultados(x.length);
	
	// Recorremos todos los elementos del XML
	
	for (i=0;i<x.length;i++)
	{

		for (j=0;j<x[i].childNodes.length;j++)
		{
			if (x[i].childNodes[j].nodeType != 1) continue;

			if (x[i].childNodes[j].nodeName == "sector") {
			
				sector = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "latitud") {
			
				latitud = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "longitud") {
			
				longitud = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "nombre") {
			
				nombre = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "categoria") {
			
				categoria = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "subcategoria") {
			
				subcategoria = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "id_empresa") {
			
				id_empresa = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "foto_muestra") {
			
				foto_muestra = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			if (x[i].childNodes[j].nodeName == "url_ficha_completa") {
			
				url_ficha_completa = x[i].childNodes[j].firstChild.nodeValue;
				
			}
			
		} // end for

		// Levantamos la bandera para el sector de este elemento
		
		markerGroupsFlags[sector] = true;
		
		// Introducimos el nuevo marcador en el grupo temporal, dentro de su categoría
		
		markerGroupsTemp[sector].push(crearMarcador(new GLatLng(latitud, longitud), sector, nombre, categoria, subcategoria, id_empresa, foto_muestra, url_ficha_completa));
		
	} // end for
	
	// Para cada categoría verificamos si existen elementos nuevos en la nueva remesa de datos,
	// en cuyo caso eliminaremos los marcadores existentes previamente para dicha categoría.

	// Si hay nuevos elementos y además había marcadores en dicha categoría:

	for (var sector in markerGroupsFlags) {
	
		if (markerGroupsFlags[sector] && markerGroups[sector].length > 0) {
		
			eliminarMarcadoresDelGrupo(sector);
			vaciarGrupoDeMarcadores(sector);

		}

    } // end for

	// Para cada sector cargamos en el grupo de marcadores los nuevos elementos provenientes del grupo temporal

	for (var sector in markerGroupsTemp) {

		for (var i = 0; i < markerGroupsTemp[sector].length; i++) {
		
			// Añadimos el marcador al mapa
		
			map.addOverlay(markerGroupsTemp[sector][i]);
			
			// Agregamos el marcador al grupo de marcadores

			markerGroups[sector].push(markerGroupsTemp[sector][i]);
	
		}
		
		// Vaciamos el grupo temporal para esta categoría
		
		vaciarGrupoDeMarcadoresTemporal(sector);

    } // end for
    
    var contador_marcadores = 0;
    
	// Para cada categoría establecemos los toggle en la situación que deben estar
    
	for (var sector in markerGroupsFlags) {
	
		// Si el grupo tiene al menos un elemento
	
		if (markerGroups[sector].length > 0) {
		
			contador_marcadores = contador_marcadores + markerGroups[sector].length;
		
			// Si en esta carga se ha cargado algún elemento de este grupo, lo seleccionamos
		
			if (markerGroupsFlags[sector]) {
		
				document.getElementById("toggle-" + sector).className = "seleccionado";
				
			}
			
		// Si el grupo no tiene ningún elemento se desactiva
		
		} else {
		
			document.getElementById("toggle-" + sector).className = "desactivado";
		
		}
	
	} // end for
	
	// Si hay al menos un marcador centramos el mapa

	if (contador_marcadores > 0) {

		centrarMapa();
	
	}
	
} // end function




function centrarMapa() {

	//	var markerLatLng = { "lat": [], "lng": [] };

	var lat_mayor = -1000;
	var lat_menor = 1000;
	var lng_mayor = -1000;
	var lng_menor = 1000;

	// Para cada categoría

	for (var sector in markerGroups) {

		for (var i = 0; i < markerGroups[sector].length; i++) {
		
			latlng_temp = markerGroups[sector][i].getLatLng();
			
			lat_temp = latlng_temp.lat();
			lng_temp = latlng_temp.lng();
			
			//if (lat_temp < 0) {
			
				if (lat_temp < lat_menor) {
				
					lat_menor = lat_temp;
				
				}
			
			//}

			//if (lat_temp >= 0) {
			
				if (lat_temp > lat_mayor) {
				
					lat_mayor = lat_temp;
				
				}
			
			//}

			//if (lng_temp < 0) {
			
				if (lng_temp < lng_menor) {
				
					lng_menor = lng_temp;
				
				}
			
			//}

			//if (lng_temp >= 0) {
			
				if (lng_temp > lng_mayor) {
				
					lng_mayor = lng_temp;
				
				}
			
			//}
			
		}		

	} // end for



	//markerLatLng[lat].push(lat_temp));
	//markerLatLng[lng].push(lng_temp));
	
	lat_media = parseFloat(((lat_mayor - lat_menor) / 2)) + parseFloat(lat_menor);
	lng_media = parseFloat(((lng_menor - lng_mayor) / 2)) + parseFloat(lng_mayor);


	//	alert(lat_menor + "," + lng_mayor);
	//	alert(lat_mayor + "," + lng_menor);
	//	alert(lat_media + "@" + lng_media);
	
	map_bounds = new GLatLngBounds(new GLatLng(lat_menor, lng_menor), new GLatLng(lat_mayor, lng_mayor));

	map_zoom = map.getBoundsZoomLevel(map_bounds);

	if (map_zoom > 15) {
	
		map_zoom = 15;
	
	}
	
	if (map_zoom < 10 ) {
	
		map_zoom = 10;
	
	}

	map.panTo(new GLatLng(lat_media, lng_media));
	
	map.setCenter(new GLatLng(lat_media, lng_media), map_zoom);
	
	//map.setZoom(map_zoom);
	

	//map.setCenter(new GLatLng(lat_media, lng_media), map_zoom);

	//alert(map.GLatLngBounds.getSouthWest());

} // end function


function crearMarcador(coordenada, sector, nombre, categoria, subcategoria, id_empresa, foto_muestra, url_ficha_completa) {

	var icono = new GIcon();
	
	switch (sector){
	case "alojamiento":
	
		icono.image = "/img/marcador_alojamiento.png";
		icono.iconSize = new GSize(22, 37);
	
	break;
	case "ocio":
	
		icono.image = "/img/marcador_ocio.png";
		icono.iconSize = new GSize(21, 37);
	
	break;
	case "gastronomia":
	
		icono.image = "/img/marcador_gastronomia.png";
		icono.iconSize = new GSize(22, 37);
	
	break;
	case "comercio":
	
		icono.image = "/img/marcador_comercio.png";
		icono.iconSize = new GSize(21, 37);
	
	break;
	case "servicios":
	
		icono.image = "/img/marcador_servicios.png";
		icono.iconSize = new GSize(22, 37);
	
	break;
	}
	
	icono.shadow = "http://www.google.com/mapfiles/shadow50.png";
	
	icono.shadowSize = new GSize(37, 34);
	icono.iconAnchor = new GPoint(10, 34);
	icono.infoWindowAnchor = new GPoint(12, 3);
	icono.infoShadowAnchor = new GPoint(18, 25);

	var marker = new GMarker(coordenada, icono);
	
	html_ficha = '<div class="ficha-en-mapa">' + '<img src="../../../archivos/imagenes/muestra/' + foto_muestra + '"/>' + '<p><a href="../../' + url_ficha_completa + '">' + nombre + '</a></p>' + '<p class="tipo"><span class="categoria">' + categoria + '</span> &raquo; <span class="subcategoria">' + subcategoria + '</span></p>' + '</div>'
	marker.bindInfoWindowHtml(html_ficha);
	
	// Con el método bindInfoWindowHtml ya se incorpora el listener
	//GEvent.addListener(marker, "click", function() {
		//html_ficha = '<div class="ficha-en-mapa">' + '<img src="media/' + foto_muestra + '"/>' + '<p><a href="' + url_ficha_completa + '">' + nombre + '</a></p>' + '<p>' + categoria + '</p>' + '<p>' + subcategoria + '</p>' + '</div>'
		//marker.openInfoWindowHtml(html_ficha);
	//});
	
	return marker;

}

function eliminarMarcadoresDelGrupo(sector) {
  for (var i = 0; i < markerGroups[sector].length; i++) {

	var marker = markerGroups[sector][i];
	marker.remove();
  } 
}

function vaciarGrupoDeMarcadores(sector) {

	markerGroups[sector].splice(0,markerGroups[sector].length);

}


function vaciarGrupoDeMarcadoresTemporal(sector) {

	markerGroupsTemp[sector].splice(0,markerGroupsTemp[sector].length);

}

function toggleGroup(elemento, sector) {
	elemento.style.display = "block";

	switch (elemento.className){
	case "seleccionado":
		elemento.className = "no_seleccionado";
	break;
	case "no_seleccionado":
		elemento.className = "seleccionado";
	break;
	}

  for (var i = 0; i < markerGroups[sector].length; i++) {
	var marker = markerGroups[sector][i];
	if (marker.isHidden()) {
	  marker.show();
	} else {
	  marker.hide();
	}
  } 
}

//
// function alertGrupos()
//
// Función de debugging para ver qué elementos hay en el grupo y en el grupo temporal

function alertGrupos() {

	cadena = ""
	cadena_temp = ""

	for (var sector in markerGroups) {
	
		cadena = cadena + sector + ": " + markerGroups[sector].length + " - ";
		
		cadena_temp = cadena_temp + sector + ": " + markerGroupsTemp[sector].length + " - ";
		
	}

	alert(cadena + "\n" + cadena_temp);

}

/*****************************************************************************************
          Script to import XML data files and make them available to JavaScript
                     v2.0.6 written by Mark Wilton-Jones, 13/04/2004
Updated 02/07/2004 to provide native Safari 1.2 and Opera 7.6 support using XMLHttpRequest
                   Updated 24/07/2004 to prevent a Safari caching bug
      Updated 02/10/2004 to include support for older Internet Explorer XML objects
 Updated 09/11/2004 to allow a delay for better response in browsers that use the iframe
               Updated 17/03/2007 to support ActiveX object used by Pocket IE
*******************************************************************************************/

var MWJ_ldD = [];

function importXML( oURL, oFunct, oNoRand, oDelay ) {

	//note: in XML importing event handlers, 'this' refers to window
	if( !oNoRand ) { oURL += ( ( oURL.indexOf('?') + 1 ) ? '&' : '?' ) + ( new Date() ).getTime(); } //prevent cache
	if( window.XMLHttpRequest ) {
		//alternate XMLHTTP request - Gecko, Safari 1.2+ and Opera 7.6+
		MWJ_ldD[MWJ_ldD.length] = new XMLHttpRequest();
		MWJ_ldD[MWJ_ldD.length-1].onreadystatechange = new Function( 'if( MWJ_ldD['+(MWJ_ldD.length-1)+'].readyState == 4 && MWJ_ldD['+(MWJ_ldD.length-1)+'].status < 300 ) { '+oFunct+'(MWJ_ldD['+(MWJ_ldD.length-1)+'].responseXML); }' );
		MWJ_ldD[MWJ_ldD.length-1].open("GET", oURL, true);
		MWJ_ldD[MWJ_ldD.length-1].send(null);
		return true;
	}
	if( !navigator.__ice_version && window.ActiveXObject ) {
		//the Microsoft way - IE 5+/Win (ICE produces errors and fails to use try-catch correctly)
		var activexlist = ['Microsoft.XMLHTTP','Microsoft.XMLDOM'], tho; //add extra progids if you need specifics
		for( var i = 0; !tho && i < activexlist.length; i++ ) {
			try { tho = new ActiveXObject( activexlist[i] ); } catch(e) {}
		}
		if( tho ) {
			MWJ_ldD[MWJ_ldD.length] = tho;
			MWJ_ldD[MWJ_ldD.length-1].onreadystatechange = new Function( 'if( MWJ_ldD['+(MWJ_ldD.length-1)+'].readyState == 4 ) { '+oFunct+'(MWJ_ldD['+(MWJ_ldD.length-1)+'].load?MWJ_ldD['+(MWJ_ldD.length-1)+']:MWJ_ldD['+(MWJ_ldD.length-1)+'].responseXML); }' );
			if( MWJ_ldD[MWJ_ldD.length-1].load ) {
				MWJ_ldD[MWJ_ldD.length-1].load(oURL);
			} else {
				MWJ_ldD[MWJ_ldD.length-1].open('GET', oURL, true);
				MWJ_ldD[MWJ_ldD.length-1].send(null);
			}
			return true;
		}
	}
	if( document.createElement && document.childNodes ) {
		//load the XML in an iframe
		var ifr = document.createElement('DIV');
		ifr.style.visibility = 'hidden'; ifr.style.position = 'absolute'; ifr.style.top = '0px'; ifr.style.left = '0px';
		//onload only fires in Opera so I use a timer for all
		if( !window.MWJ_XML_timer ) { window.MWJ_XML_timer = window.setInterval('MWJ_checkXMLLoad();',100); }
		ifr.innerHTML = '<iframe src="'+oURL+'" name="MWJ_XML_loader_'+MWJ_ldD.length+'" height="0" width="0"><\/iframe>';
		MWJ_ldD[MWJ_ldD.length] = oFunct+'MWJ_SPLIT'+(oDelay?oDelay:1)+'';
		document.body.appendChild(ifr);
		return true;
	}
	return false;
}

function MWJ_checkXMLLoad() {
	//check if each imported file is available (huge files may not have loaded completely - nothing I can do - use the delay to help)
	for( var x = 0; x < MWJ_ldD.length; x++ ) { if( MWJ_ldD[x] && window.frames['MWJ_XML_loader_'+x] ) {
		setTimeout( MWJ_ldD[x].split('MWJ_SPLIT')[0] + '(window.frames.MWJ_XML_loader_'+x+'.window.document);', parseInt(MWJ_ldD[x].split('MWJ_SPLIT')[1]) );
		MWJ_ldD[x] = false;
	} }
}
