/*
Project: HUMBOLDT GEOPISTA
File: testeador.js
Author: Angel Monterde <angel.monterde.gpl@gmail.com>
Team Geopista: 
        Jorge Elia <jorgelia82@gmail.com>
        Paula Garcia <paulicagg@gmail.com>
        Pablo Gallardo <pgallardo@geopista.es>
        Juan Martin <jmartin@geopista.es>
        Angel Monterde <angel.monterde.gpl@gmail.com>	
 
Date: 29/05/2007
 
HUMBOLDT GEOPISTA - Light WebClient/viewer for OGC Web Map Services.
Copyright (C) 2007
 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

function obtenParametro(nombreParametro){
    var regexS = "[\\?&]"+nombreParametro+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;
    var results = regex.exec( tmpURL );
    if( results == null )
        return -1;
    else
        return results[1];
}
/*
function cargaDocumento(rutaDocumento){
    if (window.ActiveXObject) {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.load(rutaDocumento);
        //getmessage();
        return xmlDoc;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation &&
    document.implementation.createDocument) {
        xmlDoc=document.implementation.createDocument("","",null);
        //var parser=new DOMParser();
        //var xmlDoc=parser.parseFromString(rutaDocumento,"text/xml");
        xmlDoc.async=false; 
        xmlDoc.contentType = "text/xml; utf-8";
        xmlDoc.load(rutaDocumento);
        //xmlDoc.onload=getmessage;
        return xmlDoc;
    }
    else {
        alert('Su navegador no puede cargar esta pagina. Utilice FireFox 2.0 o Internet Explorer 7');
    }
    /*
    dojo.io.bind({
        url: rutaDocumento,
        load: function(type, data, evt){
            return data;
        },
        async: false,
        encoding: "utf8",
        mimetype: "text/xml"
    });
    
}
*/

function obtenNodo(datosEnXML, idMunicipio){
    //var resultado = [];
    var property = datosEnXML.getElementsByTagName("property");
    for(var i=0; i<property.length; i++){
        var atributos = property[i].attributes;
        for(var j=0; j<atributos.length; j++){
            if(atributos[j].nodeValue=="INE_TXT"){
                //if(idMunicipio.substr(2,5)==(property[i].childNodes[0].nodeValue)){
                //console.log("subcadena municipio:"+idMunicipio.substr(0,4) + "nodo hijo:"+property[i].childNodes[0].nodeValue);
                if((idMunicipio.substr(0,5))==(property[i].childNodes[0].nodeValue)){
                    // devolvemos el nodo con todo el contenido
                    //resultado = property[i].parentNode;
                    var nucleo_txt = getAtributo(property[i].parentNode, "NUCLEO_TXT");
                    // geopista 1000 la invocacion al municipio es de mas de 5 caracteres
                    if(idMunicipio.length>5){
                        if(nucleo_txt==idMunicipio.substr(5)){
                            return property[i].parentNode;
                            //return property[i].parentNode;
                        }				
                    }else{
                        return property[i].parentNode;
                    }
                    break;
                }
            }
        }
    }
    return null;
}


function getAtributo(nodo, atributo){
    var propiedades = nodo.getElementsByTagName("property");
    for(var i=0; i<propiedades.length; i++){
        var atributos = propiedades[i].attributes;
        //console.log("--------------------------------------------------");
        //console.log(propiedades[i]);
        //debugger;
        //console.log("--------------------------------------------------");
        //console.log(atributos);
        if(atributos.length>0){	
            if(atributos[0].nodeValue == atributo){
                //alert(atributos.length);
                //alert(atributos[0]);
                return(dojo.dom.textContent(propiedades[i]));
            }
        }
    }
}

function getMunicipiosProvincia(evt){
    var codigoProvincia;
    if(idProvincia==null){
        codigoProvincia = dojo.byId("selectProvincia").value;
    }else{
        codigoProvincia = idProvincia;
    }
    dojo.io.bind({
        url: codigoProvincia+extFichero,
        asyn: false,
        load: function(type, data, evt){
            var selectorMunicipio = dojo.byId("selectMunicipio");
            selectorMunicipio.disabled = false;
            eliminaMunicipios();
            poblarProvincia();
            // caso del IE que no hace caso
            if(codigoMunicipio!=null){
                recuperaMunicipioYReenvia();
            }
            },
        mimetype: "text/javascript",
        encoding:"UTF-8",
        method: "POST"
    });
}
//
var vMunicipios = [];
// llamado desde el js de configuracion
function recuperaMunicipios(municipios){
    vMunicipios = municipios;
}

function poblarProvincia(){
    var selectMunicipio = dojo.byId("selectMunicipio");
    for(var i=0; i<vMunicipios.length; i++){
        var opcion = new Option(vMunicipios[i].MUN_NOM, vMunicipios[i].INE_TXT)
        selectMunicipio.options[i+1] = opcion;
    }
}

function getMunicipio(idMunicipio){
    var idPasado = idMunicipio+"";
    var rdoTemporal = null;
    
    //alert(vMunicipios.length + " idPasado:" + idPasado);
    
    for(var i=0; i<vMunicipios.length; i++){
        if(vMunicipios[i].INE_TXT == idPasado.substring(0,5)){
            if(idPasado.length!=5){
                // si tiene 9 caracteres entonces comprobamos el NUCLEO_TXT
                rdoTemporal = vMunicipios[i];
                if(vMunicipios[i].INE_TXT + vMunicipios[i].NUCLEO_TXT == idMunicipio){
                    return vMunicipios[i];
                }else{
                    continue;
                }
            }else{
                return vMunicipios[i];
            }
        }
    }
    return rdoTemporal;
}

function getCoordenadaConfig(registroMunicipio, x){
    var coordenadasXY = registroMunicipio.coordinates;
    var coordenadas = coordenadasXY.split(",");
    if(x){
        return coordenadas[0]
    }
    return coordenadas[1];
}

function poblarProvincias(){
    var selectorProvincia = dojo.byId("selectProvincia");
    var provincias = documentoProvincias.getElementsByTagName("feature");
    for(var i=0; i<provincias.length; i++){
        var nombreProvinciaOpcion = getAtributo(provincias[i], "PROV_COD");
        var idProvinciaOpcion = getAtributo(provincias[i], "PROV_NOM");
        
        var opcion = new Option(idProvinciaOpcion, nombreProvinciaOpcion);
        selectorProvincia.options[i+1] = opcion;
    }
    // reactivamos el del municipio
    //var selectorMunicipio = dojo.byId("selectMunicipio");
    //selectorMunicipio.disabled = false;
    //
    cargadaProvincias = true;
}

function agregaOpcionAProvincias(nombre, codigo){
    var opcion = new Option(nombre, codigo);
    var selectorProvincia = dojo.byId("selectProvincia");
    selectorProvincia.options[0] = opcion;
}

function redirigePeticion(municipio, nombreProvincia){
    var invocacion;
    var ficheroGeopista = municipio.FICHERO_GEOPISTA;//getAtributo(municipio, "FICHERO_GEOPISTA");
    var idMunicipio = municipio.INE_TXT;//getAtributo(municipio,"INE_TXT");
    var cadIdMunicipio = "?idMunicipio="+idMunicipio;
    if((ficheroGeopista==null)||(ficheroGeopista=="")||(ficheroGeopista.length<1)){
        var cadNombreProvincia = "&nombreProvinciaConfig="+nombreProvincia;
        xConfig = "&xConfig="+getCoordenadaConfig(municipio,true);//getXConfig(municipio);
        yConfig = "&yConfig="+getCoordenadaConfig(municipio,false);//getYConfig(municipio);
        escalaConfig = municipio.ESCALA; //getAtributo(municipio,"ESCALA");
        if(escalaConfig==""){
            escalaConfig = "&escalaConfig="+130000;
        }else{
            escalaConfig = "&escalaConfig="+escalaConfig;
        }
        nombreConfig = "&nombreConfig="+municipio.MUN_NOM;//getAtributo(municipio, "MUN_NOM");
        srsConfig = "&srsConfig="+municipio.SRS;//+getAtributo(municipio, "SRS");
        invocacion = direccion+cadIdMunicipio+xConfig+yConfig+escalaConfig+nombreConfig+srsConfig+cadNombreProvincia; 
    }else{
        invocacion = direccion2 +cadIdMunicipio;
    }
    
    var x = obtenParametro("x");
    var y = obtenParametro("y");
    var escala = obtenParametro("escala");
    var tipoChincheta = obtenParametro("tipoChincheta");
    
    if((x!=-1)&&(y!=-1)&&(escala!=-1)){
        invocacion += "&x="+x+"&y="+y+"&escala="+escala;
        if(tipoChincheta!=-1){
            invocacion+="&tipoChincheta="+tipoChincheta;
        }
    }    
    
    vMunicipios = null;
    documentoProvincias = null;
    
    window.location.href = invocacion;
}

function obtenerNombreProvincia(idProvincia){
    var provincias = documentoProvincias.getElementsByTagName("feature");
    for(var i=0; i<provincias.length; i++){
        codProvincia = getAtributo(provincias[i], "PROV_COD");
        if(codProvincia==idProvincia){
            var nombreProvincia = getAtributo(provincias[i], "PROV_NOM");
            return(nombreProvincia);
        }
    }
}

function eliminaMunicipios(){
    var selectorMunicipio = dojo.byId("selectMunicipio");
    var opciones = selectorMunicipio.getElementsByTagName("OPTION");
    var nelementos = opciones.length;
    for(var i=0; i<nelementos; i++){
        selectorMunicipio.removeChild(opciones[0]);
    }
    var opcion = new Option("Seleccione un municipio", -1);
    selectorMunicipio.options[0] = opcion;
}

function recuperaMunicipioYReenvia(){
    var municipio = getMunicipio(codigoMunicipio);
    // si existe el municipio
    if(municipio!=null){
        // recuperar los datos del municipio
        redirigePeticion(municipio, nombreProvincia);
    }else{
        // no existe el municipio, se muestra la lista con todos 
        // los municipios 
        //getMunicipiosProvincia(null);
        agregaOpcionAProvincias(nombreProvincia,codProvincia);
        //poblarProvincia();
        dojo.byId("selectProvincia").disabled=true;
        dojo.byId("selectMunicipio").disabled=false;                    
    }
}
///////////////////////////////////

var documentoProvincia = null;
var documentoProvincias = null;
var idProvincia = null;
var codigoMunicipio = null;
var nombreProvincia;

var direccion = "GeoPISTAMil.htm";
var direccion2 = "geopista.htm";
var cargadaProvincias = false;
var cargadaProvincia = false;
var ficheroProvincias = "provincias.jml"
var extFichero = ".js";


function inicializa(){
    // coger el codigo del municipio para obtener de este el id de la provincia
    idLocalidad = obtenParametro("idLocalidad");
    //documentoProvincias = cargaDocumento(ficheroProvincias);
    // si es -1 entonces cargar los elementos del selector.
    //if(idLocalidad==-1){
        //poblarProvincias();
    //}else{
    if(idLocalidad!=-1){
        // coger los dos primeros digitos
        idProvincia = idLocalidad.substring(0,2);
        var provincias = dojo.byId("selectProvincia").options;
        //var provincias = documentoProvincias.getElementsByTagName("feature");
        //documentoProvincia = cargaDocumento(idProvincia+extFichero);
        var existeProvincia = false;
        
        var codProvincia;

        for(var i=0; i<provincias.length; i++){
            //codProvincia = getAtributo(provincias[i], "PROV_COD");
            codProvincia = provincias[i].value;
            if(codProvincia==idLocalidad.substring(0,2)){
                existeProvincia = true;
                //nombreProvincia = getAtributo(provincias[i], "PROV_NOM");
                nombreProvincia = provincias[i].text;
                break;
            }
        }
        if(existeProvincia){
            //documentoProvincia = cargaDocumento(idProvincia+extFichero);
            getMunicipiosProvincia(idProvincia);
            // ej 		04062
            if(idLocalidad.length>=5){
                if(idLocalidad.length==9){
                    codigoMunicipio = idLocalidad;
                }else{
                    codigoMunicipio = idLocalidad.substr(0,5);
                }
                
                recuperaMunicipioYReenvia();
                //buscar si existe dicho municipio
                //var municipio = obtenNodo(documentoProvincia, codMunicipio);
                /*var municipio = getMunicipio(codigoMunicipio);
                // si existe el municipio
                if(municipio!=null){
                    // recuperar los datos del municipio
                    redirigePeticion(municipio, nombreProvincia);
                }else{
                    // no existe el municipio, se muestra la lista con todos 
                    // los municipios 
                    //getMunicipiosProvincia(null);
                    agregaOpcionAProvincias(nombreProvincia,codProvincia);
                    //poblarProvincia();
                    dojo.byId("selectProvincia").disabled=true;
                    dojo.byId("selectMunicipio").disabled=false;                    
                }*/
            }else{
            //si la longitud es de 9
                //getMunicipiosProvincia(null);
                agregaOpcionAProvincias(nombreProvincia,codProvincia);
                //poblarProvincia();
                dojo.byId("selectProvincia").disabled=true;
                dojo.byId("selectMunicipio").disabled=false;
            }
        }else{
            //poblarProvincias();
        }
    }
    //dojo.event.kwConnect({srcObj: dojo.byId("selectProvincia"), srcFunc: "onchange", adviceFunc: "activaSelectorMunicipio", once:true});
    dojo.event.kwConnect({srcObj: dojo.byId("selectProvincia"), srcFunc: "onchange", adviceFunc: "getMunicipiosProvincia", once:true});
    dojo.event.connect(dojo.byId("btnIrAlMunicipio"), "onclick", "irAlMunicipio");
}
/*
function activaSelectorMunicipio(evt){
    var selectorProvincia = evt.currentTarget;
    // si ha seleccionado una opcion valida
    if((selectorProvincia.options[selectorProvincia.selectedIndex].value)!="-1"){
        var selectorMunicipio = dojo.byId("selectMunicipio");
        selectorMunicipio.disabled = false;
        eliminaMunicipios();
        documentoProvincia = cargaDocumento(selectorProvincia.options[selectorProvincia.selectedIndex].value+extFichero);
        poblarProvincia();
    }
}
*/
function irAlMunicipio(){
    var selectorProvincia = dojo.byId("selectProvincia");
    var selectorMunicipio = dojo.byId("selectMunicipio");
    
    if(((selectorProvincia.options[selectorProvincia.selectedIndex].value)!="-1")&&
    ((selectorMunicipio.options[selectorMunicipio.selectedIndex].value)!="-1")){
        //var municipio = obtenNodo(documentoProvincia, selectorMunicipio.options[selectorMunicipio.selectedIndex].value);
        var municipio = getMunicipio(selectorMunicipio.options[selectorMunicipio.selectedIndex].value);
        var nombreProvincia = selectorProvincia.options[selectorProvincia.selectedIndex].text;
        redirigePeticion(municipio, nombreProvincia);
    }
}
