function selMuni(idMuni){
	id_municipio = idMuni;
	//Marcamos en la lista el municipio seleccionado en Rojo
	$.each($('.municipios .listado li[id*=muni]'), function() {
		this.firstChild.style.color = "#555555";
	});
	document.getElementById('muni'+idMuni).firstChild.style.color = "#CB062B";
	//Ocultamos el mapa
	$('.divMapa').hide();
	$('.mapaSombra').hide();
	//Ocultamos el infoComunidad
	$('.infoMuniCont .infoComunidad').hide();
	//Mostramos el infoMuni correspondiente
	$.each($('.infoMuniCont div[id*=info]'), function() {
		this.style.display = "none";
	});
	document.getElementById('info'+idMuni).style.display = "block";
	$('select[name=selEstadistica]').val('1');
	cargaEstadistica();
	cargaResumenEstadistica();

	//$('.botonNacional img').attr('src','/images/botonComunidad.gif');
	$('.botonComunidad').show();
	
	selLogo(idMuni);
}

function selComu(){
	id_municipio = '0';
	//Marcamos todos los municipios de la lista en Gris
	$.each($('.municipios .listado li[id*=muni]'), function() {
		this.firstChild.style.color = "#555555";
	});
	//Mostramos el mapa
	$('.divMapa').show();
	$('.mapaSombra').show();
	//Ocultamos los infoMuni
	$.each($('.infoMuniCont div[id*=info]'), function() {
		this.style.display = "none";
	});
	//Mostramos el infoComunidad
	$('.infoMuniCont .infoComunidad').show();
	$('select[name=selEstadistica]').val('0');
	cargaEstadistica();
	cargaResumenEstadistica();

	//$('.botonNacional img').attr('src','/images/botonNacional.gif');
	$('.botonComunidad').hide();
	selLogo('0');
}

function selNacion(){
	document.location = '/';
	/*
	if(id_municipio == '0'){
		document.location = '/';
	}else{
		selComu();
	}
	*/
}

function selLogo(idMuni){
	//Ocultamos todos
	$('.columnaIzqda .logo').each(function(){
		$(this).hide();
	});
	if(idMuni=='0'){
		//Mostramos el de la comunidad
		$('.columnaIzqda .logoComu').show();
	}else{
		if ($('.columnaIzqda .logo'+idMuni).length){
			//Mostramos el del municipio si existe
			$('.columnaIzqda .logo'+idMuni).show();
		}else{
			//Si el municipio no tiene logo, mostramos el de la comunidad
			//$('.columnaIzqda .logoComu').show();
		}
	}
}

function filtrarMuni(valComu){
	//$("select[name='municipio']").removeOption(/[^0]/);
	$("select[name='municipio']").removeOption(/^./);
	if(valComu == '0'){
		for(var j= 0; j < comunidades.length; j++){
			for(var i= 0; i < municipios[comunidades[j]].length; i++){
				var muni = municipios[comunidades[j]][i].split('#');
				$("select[name='municipio']").addOption(valComu+'#'+muni[0], muni[1]);
			}
		}
	}else{
		if(municipios[valComu]){
			for(var i= 0; i < municipios[valComu].length; i++){
				var muni = municipios[valComu][i].split('#');
				$("select[name='municipio']").addOption(valComu+'#'+muni[0], muni[1]);
			}
		}
	}
	$("select[name='municipio']").sortOptions();
	$("select[name='municipio']").html('<option value="0" selected="selected">Seleccionar</option>'+$("select[name='municipio']").html());
	$("select[name='municipio']").selectOptions("0");
}

function removeAccents(strAccents){
    strAccents = strAccents.split('');
    strAccentsOut = new Array();
    strAccentsLen = strAccents.length;
    var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    var accentsOut = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
    for (var y = 0; y < strAccentsLen; y++) {
        if (accents.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
        }
        else
            strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');
    return strAccentsOut;
}

function irComunidad(){
	var comunidad = $('select[name=comunidad] option:selected').val();

	if(comunidad == '0'){
		alert('Debe seleccionar una comunidad autónoma.');
	}
	else{
		var destino = "/";
		switch (comunidad) {
			case '1':
				destino += "andalucia";
				break;
			case '2':
				destino += "aragon";
				break;
			case '3':
				destino += "principadodeasturias";
				break;
			case '4':
				destino += "islasbaleares";
				break;
			case '5':
				destino += "canarias";
				break;
			case '6':
				destino += "cantabria";
				break;
			case '7':
				destino += "castillayleon";
				break;
			case '8':
				destino += "castillalamancha";
				break;
			case '9':
				destino += "catalunya";
				break;
			case '10':
				destino += "comunidadvalenciana";
				break;
			case '11':
				destino += "extremadura";
				break;
			case '12':
				destino += "galicia";
				break;
			case '13':
				destino += "comunidaddemadrid";
				break;
			case '14':
				destino += "regiondemurcia";
				break;
			case '15':
				destino += "comunidadforalnavarra";
				break;
			case '16':
				destino += "paisvasco";
				break;
			case '17':
				destino += "larioja";
				break;
			case '18':
				destino += "ceuta";
				break;
			case '19':
				destino += "melilla";
				break;
			default:
				destino += "comunidad/"+comunidad;
				break;
		} 		
		location.href = destino;
	}
}

function irMunicipio(){
	var municipio = $('select[name=municipio] option:selected').val();
	if(municipio == '0'){
		alert('Debe seleccionar un municipio.');
	}else{
		partesMuni = municipio.split('#');
		var destino = "/";
		switch (partesMuni[0]) {
			case '1':
				destino += "andalucia";
				break;
			case '2':
				destino += "aragon";
				break;
			case '3':
				destino += "principadodeasturias";
				break;
			case '4':
				destino += "islasbaleares";
				break;
			case '5':
				destino += "canarias";
				break;
			case '6':
				destino += "cantabria";
				break;
			case '7':
				destino += "castillayleon";
				break;
			case '8':
				destino += "castillalamancha";
				break;
			case '9':
				destino += "catalunya";
				break;
			case '10':
				destino += "comunidadvalenciana";
				break;
			case '11':
				destino += "extremadura";
				break;
			case '12':
				destino += "galicia";
				break;
			case '13':
				destino += "comunidaddemadrid";
				break;
			case '14':
				destino += "regiondemurcia";
				break;
			case '15':
				destino += "comunidadforalnavarra";
				break;
			case '16':
				destino += "paisvasco";
				break;
			case '17':
				destino += "larioja";
				break;
			case '18':
				destino += "ceuta";
				break;
			case '19':
				destino += "melilla";
				break;
			default:
				destino += "comunidad/"+comunidad;
				break;
		} 		
		location.href = destino+"/"+partesMuni[1];
		//location.href = "/comunidad/"+partesMuni[0]+"/"+partesMuni[1];
	}
}

function buscarMunicipio(tecla){
	if(tecla != null && tecla != 13){
		return 0;
	}
	var municipio = $.trim($('input[name=municipio]').val());
	if(municipio == ''){
		alert('Debe introducir un nombre para buscar.');
	}else{
		popupCssShow('buscarMunicpio.php?cadena='+encodeURIComponent(municipio), 460);
	}
}

function cargaKml(mapa,url,urlBase,nombreFichero){
	 var xml = null;
	 try{
		 xml = new ActiveXObject("Microsoft.XMLHTTP");
	 }catch(expeption){
		 xml = new XMLHttpRequest();
	 }
	 var fecha = new Date();
	 //document.getElementById('mapaInicial').innerHTML = 'Generando mapa..'; 
	 xml.onreadystatechange=function(){
		if (xml.readyState==4 || xml.readyState=="complete")
		 { 
			
			//alert(xml.responseText);
			
			if (xml.responseText.substring(0,12)=='contFicheros')
			{
				var numFicheros = parseInt(xml.responseText.substring(13,15));
				if(nombreFichero == ''){
					nombreFichero = "kmlFicha"+fecha.getTime()+"_1.kml";
				}
				mapa.addOverlay(new GGeoXml(urlBase+nombreFichero));
			}else{
				//Habrá algún error
				//document.getElementById('mapaInicial').innerHTML = xml.responseText;
			}
		 } 
	 };
	 xml.open("GET",url+"&f="+fecha.getTime(), true);
	 xml.send(null);

}

function anadirMunicipio(){
	var municipio = $('select[name=municipio] option:selected').val();
	if(municipio == '0'){
		alert('Debe seleccionar 1 municipio.');
	}else{
		if($("select[name='municipiosComp']").find("option").length == 5){
			alert('Sólo es posible seleccionar un máximo de 5 municipios.');
		}else{
			var municipioNombre = $('select[name=municipio] option:selected').text();
			if(!$("select[name='municipiosComp']").containsOption(municipio)){
				$("select[name='municipiosComp']").addOption(municipio, municipioNombre);
				$("select[name='municipiosComp']").sortOptions();
				$("select[name='municipiosComp']").selectOptions("",true);
			}
		}
	}
}

function eliminarMunicipio(){
	var municipio = $('select[name=municipiosComp] option:selected').val();
	if(municipio == null){
		alert('Debe seleccionar 1 municipio.');
	}else{
		$("select[name='municipiosComp']").removeOption(municipio);
	}
}

function anadirComunidad(){
	var comunidad = $('select[name=comunidad] option:selected').val();
	if(comunidad == '0'){
		alert('Debe seleccionar 1 comunidad.');
	}else{
		if($("select[name='comunidadesComp']").find("option").length == 5){
			alert('Sólo es posible seleccionar un máximo de 5 comunidades.');
		}else{
			var comunidadNombre = $('select[name=comunidad] option:selected').text();
			if(!$("select[name='comunidadesComp']").containsOption(comunidad)){
				$("select[name='comunidadesComp']").addOption(comunidad, comunidadNombre);
				$("select[name='comunidadesComp']").sortOptions();
				$("select[name='comunidadesComp']").selectOptions("",true);
			}
		}
	}
}

function eliminarComunidad(){
	var comunidad = $('select[name=comunidadesComp] option:selected').val();
	if(comunidad == null){
		alert('Debe seleccionar 1 comunidad.');
	}else{
		$("select[name='comunidadesComp']").removeOption(comunidad);
	}
}

function anadirVariable(){
	var variable = $('select[name=variablesCompS] option:selected').val();
	if(variable == null){
		alert('Debe seleccionar una variable.');
	}else{
		if($("select[name='variablesCompD']").find("option").length == 5){
			alert('Sólo es posible seleccionar un máximo de 5 variables.');
		}else{
			var variableNombre = $('select[name=variablesCompS] option:selected').text();
			$("select[name='variablesCompS']").removeOption(variable);
			$("select[name='variablesCompD']").addOption(variable, variableNombre);
			ordenarVariables($("select[name='variablesCompD']")[0],variablesMunicipio);
			$("select[name='variablesCompD']").selectOptions("",true);
		}
	}
}

function eliminarVariable(){
	var variable = $('select[name=variablesCompD] option:selected').val();
	if(variable == null){
		alert('Debe seleccionar una variable.');
	}else{
		var variableNombre = $('select[name=variablesCompD] option:selected').text();
		$("select[name='variablesCompD']").removeOption(variable);
		$("select[name='variablesCompS']").addOption(variable, variableNombre);
		ordenarVariables($("select[name='variablesCompS']")[0],variablesMunicipio);
		$("select[name='variablesCompS']").selectOptions("",true);
	}
}

function anadirAno(){
	var ano = $('select[name=anosCompS] option:selected').val();
	if(ano == null){
		alert('Debe seleccionar un ano.');
	}else{
		if($("select[name='anosCompD']").find("option").length == 5){
			alert('Sólo es posible seleccionar un máximo de 5 anos.');
		}else{
			var anoNombre = $('select[name=anosCompS] option:selected').text();
			$("select[name='anosCompS']").removeOption(ano);
			$("select[name='anosCompD']").addOption(ano, anoNombre);
			$("select[name='anosCompD']").sortOptions();
			$("select[name='anosCompD']").selectOptions("",true);
		}
	}
}

function eliminarAno(){
	var ano = $('select[name=anosCompD] option:selected').val();
	if(ano == null){
		alert('Debe seleccionar un ano.');
	}else{
		var anoNombre = $('select[name=anosCompD] option:selected').text();
		$("select[name='anosCompD']").removeOption(ano);
		$("select[name='anosCompS']").addOption(ano, anoNombre);
		$("select[name='anosCompS']").sortOptions();
		$("select[name='anosCompS']").selectOptions("",true);
	}
}

function ordenarVariables(select,arrayVariables){
	var opciones = new Array();
	for(var i = 0; i<select.options.length; i++){
		opciones.push(new Array(select.options[i].value,select.options[i].text));
	}
	$(select).removeOption(/./); // remove all options
	for(var i = 0; i<arrayVariables.length; i++){
		for (x = 0; x < opciones.length; x++) {
			if(opciones[x][0]==arrayVariables[i][0]){
				$(select).addOption(opciones[x][0], opciones[x][1]);
			}
		}
	}
}
