/*
Project: HUMBOLDT GEOPISTA
File: initVisor.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 isIE(){
    // si entra es que es Mozilla, Safari, Opera o IE 7
    if(typeof document.body.style.maxHeight != "undefined"){
        IE = false;
    }else{
        // IE 6 y navegadores viejos
        IE = true;
    }
}


function initMaximizaVisor(){
    // maximizamos la ventana
    this.self.moveTo(0,0);
    this.self.resizeTo(screen.availWidth, screen.availHeight);
}

function initTamanoCapas(){
    
    var capaPadre = dojo.byId("capaPadre");
    
    var withCapaPadre = dojo.html.getViewport("capaPadre").width;
    var heightCapaPadre = dojo.html.getViewport("capaPadre").height;

    capaPadre.style.top = "0px";
    capaPadre.style.left = "0px";
    capaPadre.style.width = withCapaPadre + "px";
    capaPadre.style.height = heightCapaPadre + "px";
    
    capaPadre.style.position = "absolute";
    
    var capaPadreLeyendas = dojo.byId("capaPadreLeyendas");
    capaPadreLeyendas.style.width = WIDTH_LEYENDA + "px";
    capaPadreLeyendas.style.height = (heightCapaPadre - HEIGHT_ARRIBA)+"px";
    capaPadreLeyendas.style.top = HEIGHT_ARRIBA + "px";
    capaPadreLeyendas.style.left = 0+ "px";
    capaPadreLeyendas.style.zIndex = 600;
    
    initCreaLeyendas(capaPadreLeyendas);
    // fin de inicializaciï¿½ de la inicializaciï¿½ de la capa leyendas
    
    var capaPadreArriba = dojo.byId("capaPadreArriba");
    
    capaPadreArriba.style.width = withCapaPadre + "px";
    capaPadreArriba.style.height = HEIGHT_ARRIBA+"px";
    capaPadreArriba.style.top = 0 + "px";
    capaPadreArriba.style.left = 0+ "px";
    capaPadreArriba.style.zIndex = 600;
    
    initArriba();
    // ahora el mapa
    
    var capaPadreMapas = dojo.byId("capaPadreMapas");
    capaPadreMapas.style.width = (withCapaPadre - WIDTH_LEYENDA)+"px";
    capaPadreMapas.style.height = (heightCapaPadre - HEIGHT_ARRIBA)+"px";
    capaPadreMapas.style.top = HEIGHT_ARRIBA + "px";
    capaPadreMapas.style.left = WIDTH_LEYENDA + "px";
    capaPadreMapas.style.zIndex = 1;
    /////////////////////////////////////////////////////////////////
}

// funciï¿½ para crear las leyendas desplegables
function initCreaLeyendas(capaPadreLeyendas){
    
    // primero juntamos las leyendas globales con la especï¿½ica del municipio
    var leyendasGlobales = new Object();
    leyendasGlobales.leyenda = [];
    //leyendasGeopista
    for(var i=0;i<leyendas.leyenda.length; i++){
        var nLeyenda = new Object();
        nLeyenda.idLeyenda = leyendas.leyenda[i].idLeyenda;
        nLeyenda.texto = leyendas.leyenda[i].texto;
        if(leyendas.leyenda[i].checkboxActivo!=undefined){
            nLeyenda.checkboxActivo =leyendas.leyenda[i].checkboxActivo;
        }else{
            // si no existe le damos por defecto que esté activo.
            nLeyenda.checkboxActivo = true;
        }
        
        if(leyendas.leyenda[i].desplegado!=undefined){
            nLeyenda.desplegado =leyendas.leyenda[i].desplegado;
        }else{
            // si no existe le damos por defecto que esté activo.
            nLeyenda.desplegado = true;
        }
        
        nLeyenda.iconos = [];
        for(var j=0; j<leyendas.leyenda[i].iconos.length; j++){
            var nIcono = new Object();
            nIcono.idIcono = leyendas.leyenda[i].iconos[j].idIcono;
            nIcono.width = leyendas.leyenda[i].iconos[j].width;
            nIcono.height = leyendas.leyenda[i].iconos[j].height;
            nIcono.src = leyendas.leyenda[i].iconos[j].src;
            nIcono.texto = leyendas.leyenda[i].iconos[j].texto;
            nLeyenda.iconos.push(nIcono);
        }
        leyendasGlobales.leyenda.push(nLeyenda);
    }
    
    // ahora hacemos lo mismo pero con la leyenda especï¿½ica
    if(leyendasGeopista!=null){
        for(var i=0;i<leyendasGeopista.leyenda.length; i++){
            var nLeyenda = new Object();
            nLeyenda.idLeyenda = leyendasGeopista.leyenda[i].idLeyenda;
            nLeyenda.texto = leyendasGeopista.leyenda[i].texto;
            //debugger;
            if(leyendasGeopista.leyenda[i].checkboxActivo!=undefined){
                nLeyenda.checkboxActivo =leyendasGeopista.leyenda[i].checkboxActivo;
            }// si no existe nos quedamos con el del padre
            
            if(leyendasGeopista.leyenda[i].desplegado!=undefined){
                nLeyenda.desplegado =leyendasGeopista.leyenda[i].desplegado;
            }
            
            nLeyenda.iconos = [];
            for(var j=0; j<leyendasGeopista.leyenda[i].iconos.length; j++){
                var nIcono = new Object();
                nIcono.idIcono = leyendasGeopista.leyenda[i].iconos[j].idIcono;
                nIcono.width = leyendasGeopista.leyenda[i].iconos[j].width;
                nIcono.height = leyendasGeopista.leyenda[i].iconos[j].height;
                nIcono.src = leyendasGeopista.leyenda[i].iconos[j].src;
                nIcono.texto = leyendasGeopista.leyenda[i].iconos[j].texto;
                nLeyenda.iconos.push(nIcono);
            }
            
            // ahora buscamos ese idLeyenda entre las leyendas globales, y si lo encontramos
            // lo que hacemos es aï¿½dir los nuevos iconos
            for(var k=0; k<leyendasGlobales.leyenda.length; k++){
                if(leyendasGlobales.leyenda[k].idLeyenda == nLeyenda.idLeyenda){
                    // checkboxActivo da prevalencia al hijo sobre el padre
                    if(nLeyenda.checkboxActivo!=undefined){
                        leyendasGlobales.leyenda[k].checkboxActivo = nLeyenda.checkboxActivo;
                    }
                    
                    if(nLeyenda.desplegado!=undefined){
                        leyendasGlobales.leyenda[k].desplegado = nLeyenda.desplegado;
                    }
                    
                    for(var l =0; l <nLeyenda.iconos.length; l++){
                        leyendasGlobales.leyenda[k].iconos.push(nLeyenda.iconos[l]);
                    }
                }
                // si no encontramos esa leyenda nueva
                if(k == leyendasGlobales.length){
                    leyendasGlobales.leyenda.push(nLeyenda);    
                }
            }        
        }
    }
    
    for(var i=0; i<leyendasGlobales.leyenda.length; i++){
        //debugger;
        var capaChkLeyenda = document.createElement("div");
        var capaLeyenda = document.createElement("div");
        var chkLeyenda = document.createElement("input");
        var txtChkLeyenda = document.createTextNode(" "+leyendasGlobales.leyenda[i].texto);
        
        capaLeyenda.setAttribute('id', leyendasGlobales.leyenda[i].idLeyenda);
        capaChkLeyenda.setAttribute('id', 'div'+leyendasGlobales.leyenda[i].idLeyenda);
        chkLeyenda.setAttribute('id', 'chk'+leyendasGlobales.leyenda[i].idLeyenda);
        chkLeyenda.setAttribute('type', 'checkbox');
        dojo.html.setClass(capaChkLeyenda, 'etiquetaTitlePane');
        
        capaChkLeyenda.style.width = WIDTH_LEYENDA + "px";
        capaLeyenda.style.width = WIDTH_LEYENDA + "px";
        
        // tenemos que meter los iconos dentro de capaLeyenda
        for(var j=0; j<leyendasGlobales.leyenda[i].iconos.length; j++){
            var icono = document.createElement("img");
            var txtIcono = document.createTextNode(" "+leyendasGlobales.leyenda[i].iconos[j].texto);
            var saltoLinea = document.createElement("br");
            icono.setAttribute('id', leyendasGlobales.leyenda[i].iconos[j].idIcono);
            icono.style.width = leyendasGlobales.leyenda[i].iconos[j].width;
            icono.style.height = leyendasGlobales.leyenda[i].iconos[j].height;
            icono.src = leyendasGlobales.leyenda[i].iconos[j].src;
            
            capaLeyenda.appendChild(icono);
            capaLeyenda.appendChild(txtIcono);
            capaLeyenda.appendChild(saltoLinea);
        }
        
        capaPadreLeyendas.appendChild(capaChkLeyenda);
        capaChkLeyenda.appendChild(chkLeyenda);
        capaChkLeyenda.appendChild(txtChkLeyenda);
        capaPadreLeyendas.appendChild(capaLeyenda); 
        
        var idChk = "chk"+capaLeyenda.id;
        var titlePane = dojo.widget.createWidget("titlePane", {label: "Leyenda", labelNodeClass:"conBarraInferior", open: leyendasGlobales.leyenda[i].desplegado }, capaLeyenda);
        var chkBox = dojo.widget.createWidget("checkBox", {checked:leyendasGlobales.leyenda[i].checkboxActivo, id:idChk}, chkLeyenda);
    }
    leyendas = null;
    leyendasGeopista = null;
}

function initArriba(){
    // ponemos el logo de la FEMP bien
    var capaLogoFEMP = dojo.byId("bannersFEMP");
    capaLogoFEMP.style.position = "absolute";
    capaLogoFEMP.style.left = ((parseInt(screen.availWidth)- parseInt(dojo.byId("imgFEMP").width))-10)+"px";
    
    // el escudo del municipio
    var divMunicipio = dojo.byId("divMunicipio");
    divMunicipio.style.position = "absolute";
    var imgMunicipio = dojo.byId("imgMunicipio");
    imgMunicipio.style.position = "absolute";
    imgMunicipio.src = IMAGEN_ESCUDO_MUNICIPIO;    
    imgMunicipio.width = IMAGEN_ESCUDO_MUNICIPIO_WIDTH_PX;
    divMunicipio.style.left = (dojo.byId("imgLogoGeopista").width + 3)+"px";
    
    divMunicipio.style.width = imgMunicipio.width+"px";
    
    var divBusquedas = dojo.byId("divBusquedas");
    divBusquedas.style.position = "absolute";
    divBusquedas.style.left = (parseInt(divMunicipio.style.left)+parseInt(divMunicipio.style.width) + 2)+"px";
    var tituloBusquedas = dojo.byId("titulo");
    tituloBusquedas.innerHTML = TITULO_BUSQUEDAS;
    
    // titulo del documento
    document.title = TITULO_VISOR;
}
/*
*   Para inicializar una operacion hay que ponerlo a mano en initIconos el icono
*   que representa la operacion nueva como en geopistaInteractuadorUsuario.js en la clase 
*   GEOPISTA.Visualizacion.InteractuadorConUsuario en el metodo init.
*/
function initIconos(){
    // inicializamos nuestro almacenador de las imagenes de los iconos
    var grupoElementosIconos = new GEOPISTA.Visualizacion.GrupoElementosIconos();
    
    // Zoom Menos
    var icono = new GEOPISTA.Visualizacion.ElementoIcono("imgZoomMenos",
    "img/lupa_menos_off.gif", "img/lupa_menos_on.gif", GEOPISTA.Visualizacion.ID_ICONO_ZOOM_MENOS, false, false);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Zoom Mas  
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgZoomMas",
    "img/lupa_off.gif", "img/lupa_on.gif", GEOPISTA.Visualizacion.ID_ICONO_ZOOM, true, false);  //
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, true); //
    
    // Rubberband
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgZoomRubberband",
    "img/lupa_drag_off.gif", "img/lupa_drag_on.gif", GEOPISTA.Visualizacion.ID_ICONO_RUBBERBAND, false, false);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Cinta mÃ©trica
        /*icono = new GEOPISTA.Visualizacion.ElementoIcono("imgCintaMetrica",
        "img/undo_16.gif", "img/undo_16.gif", GEOPISTA.Visualizacion.ID_ICONO_REGLA, false, false);
        icono.refrescaImagen();
        grupoElementosIconos.addElementoIcono(icono, false);
         */
    // Mover Arriba
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgMoverArriba",
    "img/arrow-up_off.gif", "img/arrow-up_on.gif", GEOPISTA.Visualizacion.ID_ICONO_MOVER_ARRIBA, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Mano
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgMano",
    "img/mano_off.png", "img/mano_on.png", GEOPISTA.Visualizacion.ID_ICONO_MANO, false, false);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Mover Izquierda
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgMoverIzquierda",
    "img/arrow-back_off.gif", "img/arrow-back_on.gif", GEOPISTA.Visualizacion.ID_ICONO_MOVER_IZDA, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    
    // Mover Derecha
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgMoverDerecha",
    "img/arrow-forward_off.gif", "img/arrow-forward_on.gif", GEOPISTA.Visualizacion.ID_ICONO_MOVER_DCHA, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Mover Abajo
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgMoverAbajo",
    "img/arrow-down_off.gif", "img/arrow-down_on.gif", GEOPISTA.Visualizacion.ID_ICONO_MOVER_ABAJO, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    
    // Ayuntamiento
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgAyuntamiento",
    "img/home_off.gif", "img/home_on.gif",GEOPISTA.Visualizacion.ID_ICONO_AYUNTAMIENTO, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // Refrescar
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgRefrescar",
    "img/refresh_off.gif", "img/refresh_on.gif",GEOPISTA.Visualizacion.ID_ICONO_REFRESCAR, false, true);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    
    // GetFeatureInfo
/*    
    icono = new GEOPISTA.Visualizacion.ElementoIcono("imgGetFeatureInfo",
    "img/tb_italic.gif", "img/tb_italic_down.gif",GEOPISTA.Visualizacion.ID_ICONO_GET_FEATURE_INFO, false, false);
    icono.refrescaImagen();
    grupoElementosIconos.addElementoIcono(icono, false);
    */
    interactuadorConUsuario.setGrupoElementosIconos(grupoElementosIconos);
}

function ajustaBBoxATamanoActual(utmX, utmY, escala){
    //debugger;
    var capaPadreMapas = dojo.byId("capaPadreMapas");
    var widthCapaPadreMapas = parseInt(capaPadreMapas.style.width);
    var heightCapaPadreMapas = parseInt(capaPadreMapas.style.height);
    
    var cmWidthCapaPadreMapas = widthCapaPadreMapas / PIXELES_POR_CENTIMETRO ;
    var cmHeightCapaPadreMapas = heightCapaPadreMapas / PIXELES_POR_CENTIMETRO ;
    
    GEOPISTA.Base.FORMATO_IMAGEN_INICIAL = new GEOPISTA.Base.FormatoImagen(widthCapaPadreMapas,heightCapaPadreMapas,true);
    
    var distanciaX = (cmWidthCapaPadreMapas * escala)/100;
    var distanciaY = (cmHeightCapaPadreMapas * escala)/100;
    
    // ahora generamos el bbox
    var xMin = utmX - distanciaX/2;
    var yMin = utmY - distanciaY/2;
    var xMax = utmX + distanciaX/2;
    var yMax = utmY + distanciaY/2;
    
    var bbox = new GEOPISTA.Base.BBox(xMin, yMin, xMax, yMax);
    
    return bbox;
}

function inicializaCapas(/*servidorGeopista, servidoresExternos*/){
    
    // a partir de servidorGeopista y servidoresExternos habrï¿½ que construir un nuevo
    // objeto JSON en el cual fusionï¿½emos las peticiones en el campo "peticiones"
    
        /*var parametrosCapasPeticiones = {"capaMapas":"capaMapas", "capaOperacion":"capaOperacion",
          "width":"792px", "height":"540px", "position":"absolute","top":"0px", "left":"0px", 
          "imgBlanca":"img/blank.gif", "peticiones":[
                        {"idPeticion": GEOPISTA_BASE, "zIndex": 2},
                        {"idPeticion": GEOPISTA_TOPONIMOS, "zIndex": 5},
                        {"idPeticion": IDEE, "zIndex": 3}, 
                        ]
         };*/
    var parametrosCapasPeticiones = new Object();
    parametrosCapasPeticiones.capaMapas = "capaMapas";
    parametrosCapasPeticiones.capaOperacion = "capaOperacion";
    parametrosCapasPeticiones.width = dojo.byId("capaPadreMapas").style.width;
    parametrosCapasPeticiones.height = dojo.byId("capaPadreMapas").style.height;
    parametrosCapasPeticiones.position = "absolute";
    parametrosCapasPeticiones.top = "0px";
    parametrosCapasPeticiones.left = "0px";
    parametrosCapasPeticiones.imgBlanca = "img/blank.gif";//"img/transparente.png";
    parametrosCapasPeticiones.peticiones = new Array();
    
    if(CAPAS_PETICIONES_GEOPISTA!=null){
        for(var i=0; i<CAPAS_PETICIONES_GEOPISTA.peticiones.length; i++){
            var npeticion = new Object();
            npeticion.idPeticion = CAPAS_PETICIONES_GEOPISTA.peticiones[i].id;
            npeticion.idPeticion = CAPAS_PETICIONES_GEOPISTA.peticiones[i].id;
            npeticion.servidor = CAPAS_PETICIONES_GEOPISTA.peticiones[i].servidor;
            npeticion.versionGetMap = CAPAS_PETICIONES_GEOPISTA.peticiones[i].versionGetMap;
            npeticion.idMunicipio = CAPAS_PETICIONES_GEOPISTA.peticiones[i].idMunicipio;
            npeticion.zIndex = CAPAS_PETICIONES_GEOPISTA.peticiones[i].zIndex;
            npeticion.capasYEstilos = new Array();
            //console.log("pet:"+i);
            for(var j=0; j<CAPAS_PETICIONES_GEOPISTA.peticiones[i].capasYEstilos.length; j++){
                var caracteristicas = new Object();
                caracteristicas.capa = CAPAS_PETICIONES_GEOPISTA.peticiones[i].capasYEstilos[j].capa;
                caracteristicas.estilo = CAPAS_PETICIONES_GEOPISTA.peticiones[i].capasYEstilos[j].estilo;
                caracteristicas.siempreVisible = CAPAS_PETICIONES_GEOPISTA.peticiones[i].capasYEstilos[j].siempreVisible;
                caracteristicas.idLeyenda = CAPAS_PETICIONES_GEOPISTA.peticiones[i].capasYEstilos[j].idLeyenda;
                npeticion.capasYEstilos.push(caracteristicas);
            }
            parametrosCapasPeticiones.peticiones.push(npeticion);
        }
    }
    
    for(var i=0; i<CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones.length; i++){
        var npeticion = new Object();
        npeticion.idPeticion = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].id;
        npeticion.servidor = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].servidor;
        npeticion.versionGetMap = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].versionGetMap;
        npeticion.idMunicipio = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].idMunicipio;
        npeticion.zIndex = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].zIndex;
        npeticion.capasYEstilos = new Array();
        //console.log("pet:"+i);
        for(var j=0; j<CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].capasYEstilos.length; j++){
            var caracteristicas = new Object();
            caracteristicas.capa = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].capasYEstilos[j].capa;
            caracteristicas.estilo = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].capasYEstilos[j].estilo;
            caracteristicas.siempreVisible = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].capasYEstilos[j].siempreVisible;
            caracteristicas.idLeyenda = CAPAS_PETICIONES_SERVIDORES_EXTERNOS.peticiones[i].capasYEstilos[j].idLeyenda;
            npeticion.capasYEstilos.push(caracteristicas);
        }
        parametrosCapasPeticiones.peticiones.push(npeticion);
    }
    CAPAS_PETICIONES_GEOPISTA = null;
    CAPAS_PETICIONES_SERVIDORES_EXTERNOS = null;
    
    return parametrosCapasPeticiones;
}

/*
    Se inicializan en el siguiente orden los objetos:
        1- GEOPISTA.Base.ModeloCargaImagenesPeticiones
        2- GEOPISTA.Operacion.GestorOperaciones
            2-1 Relacion GEOPISTA.Operacion.GestorOperaciones con GEOPISTA.Base.ModeloCargaImagenesPeticiones
        3- GEOPISTA.Visualizacion.InteractuadorConUsuario
            3-1 Relacion GEOPISTA.Visualizacion.InteractuadorConUsuario con GEOPISTA.Operacion.GestorOperaciones
 */
function initObjetos(bboxPeticion, chincheta){
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*para desplegar:*/
    GEOPISTA.Busqueda.URL_BASE_PETICION = "http://"+GEOPISTA.Base.Servidor.GEOPISTA+"/humboldtGeopista/busqueda";
    GEOPISTA.Busqueda.PARAM_ID_MUNICIPIO = "&idMunicipio="+GEOPISTA.Base.ID_MUNICIPIO;
    // solo para desarrollo
    //GEOPISTA.Busqueda.URL_BASE_PETICION = "http://"+"192.168.10.245:8080"+"/humboldtGeopista/busqueda";
    //GEOPISTA.Busqueda.URL_BASE_PETICION = "http://"+"80.35.34.7:8080"+"/humboldtGeopista/busqueda";
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    var gestorPeticiones = new GEOPISTA.Base.GestorPeticionesGetMap(
    bboxPeticion, GEOPISTA.Base.FORMATO_IMAGEN_INICIAL, GEOPISTA.Base.SRS
    );
    
    var capasPeticiones = inicializaCapas();  
    var gestorLeyendas = null;
    var gestorComboFeatureInfo = null;
    var peticionFeatureInfo = null;
    gestorPeticiones.inicializaMunicipio(capasPeticiones);
    
    //solo depuracion, para ver quÃ© peticiones ha construido
    //peticiones = gestorPeticiones.getPeticionesMapas();

    var capaPadre = dojo.byId("capaPadreMapas");  
    
    var gestorCoordenadas = new GEOPISTA.Base.GestorCoordenadas(bboxPeticion, 
    parseInt(capasPeticiones.width), parseInt(capasPeticiones.height));  
    
    gestorCoordenadas.DESPLAZAMIENTO_X = parseInt(capaPadre.style.left);
    gestorCoordenadas.DESPLAZAMIENTO_Y = parseInt(capaPadre.style.top);
    
    var gestorImagenes = new GEOPISTA.Base.GestorImagenes(gestorPeticiones, gestorCoordenadas, IE, capaPadre, true);
    
    var capaObjetoAMostrarMientrasSeCargaPeticion = gestorImagenes.getCapaObjetoAMostrarMientrasSeCargaPeticion();
    //gestorImagenes.cargaMapas();
    var _objetoAMostrarMientrasSeCargaPeticion = creaObjetoAMostrar(parseInt(capaPadre.style.width),
    parseInt(capaPadre.style.height),capaObjetoAMostrarMientrasSeCargaPeticion);
    gestorImagenes.setObjetoAMostrarMientrasSeCargaPeticion(_objetoAMostrarMientrasSeCargaPeticion);
    
    //gestorImagenes.initPeticionConImagenes(capasPeticiones);
    gestorImagenes.initCapas(capasPeticiones);
    
    ///////////// el featureInfo
    peticionFeatureInfo = new GEOPISTA.Base.PeticionFeatureInfo(
    GEOPISTA.Base.Servidor.GEOPISTA, GEOPISTA.Base.Servidor.GEOPISTA_RUTA,
    GEOPISTA.Base.GET_FEATURE_INFO_1_1_1, 99, GEOPISTA.Base.FORMATO_SALIDA_TEXT_PLAIN,
    GEOPISTA.Base.SRS, GEOPISTA.Base.ID_MUNICIPIO);
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*
    peticionFeatureInfo = new GEOPISTA.Base.PeticionFeatureInfo(
    "192.168.10.245:8080", GEOPISTA.Base.Servidor.GEOPISTA_RUTA,
    GEOPISTA.Base.GET_FEATURE_INFO_1_1_1, 99, GEOPISTA.Base.FORMATO_SALIDA_TEXT_PLAIN,
    "&SRS=EPSG:23030", GEOPISTA.Base.ID_MUNICIPIO);
     */    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /*peticionFeatureInfo = new GEOPISTA.Base.PeticionFeatureInfo(
    "80.35.34.7:8080", GEOPISTA.Base.Servidor.GEOPISTA_RUTA,
    GEOPISTA.Base.GET_FEATURE_INFO_1_1_1, 999, GEOPISTA.Base.FORMATO_SALIDA_TEXT_PLAIN,
    "&SRS=EPSG:23030", GEOPISTA.Base.ID_MUNICIPIO);
     */////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    modeloCargaImagenesPeticiones = new  
    GEOPISTA.Base.ModeloCargaImagenesPeticiones(gestorImagenes, 
    null, peticionFeatureInfo);
    
    var ayuntamiento = new GEOPISTA.Base.Punto();
    ayuntamiento.x = GEOPISTA.Base.AYUNTAMIENTO_X;
    ayuntamiento.y = GEOPISTA.Base.AYUNTAMIENTO_Y;
    modeloCargaImagenesPeticiones.ayuntamiento = ayuntamiento;
    
    gestorOperaciones = new GEOPISTA.Operacion.GestorOperaciones(modeloCargaImagenesPeticiones);
    
    gestorLeyendas = new GEOPISTA.Visualizacion.GestorLeyendas(capasPeticiones, gestorOperaciones);
    capasPeticiones = null;
/*    
    var combo = dojo.byId("comboFeatureInfo");
    // debugger;
    gestorComboFeatureInfo = new GEOPISTA.Visualizacion.GestorComboFeatureInfo(combo, gestorOperaciones);
    gestorComboFeatureInfo.setDatos(configuracionGetFeatureInfo);
*/
    interactuadorConUsuario = new GEOPISTA.Visualizacion.InteractuadorConUsuario(gestorOperaciones, gestorLeyendas, gestorComboFeatureInfo);
    dojo.event.kwConnect({srcObj: gestorImagenes, srcFunc: "mostrarMapas", adviceObj: gestorOperaciones, adviceFunc: "recolocaChinchetas", once:true});    
    // unimos la carga del mapa con el de los iconos temporales. El modelo le avisa a la vista cuï¿½do el modelo ha cambiado su situaciï¿½.
    dojo.event.kwConnect({srcObj: gestorImagenes, srcFunc: "mostrarMapas", adviceObj: interactuadorConUsuario, adviceFunc: "refrescaElementoIcono", once:true});
    
    // le pasamos al controlador las capas seleccionadas
    dojo.event.kwConnect({srcObj: modeloCargaImagenesPeticiones, srcFunc: "borrarCapasEstilos", adviceObj: gestorLeyendas, adviceFunc: "setCapasYEstilosSeleccionadosAlControlador", once:true});
    // hay que unir el setCapaYCamposFeatureInfo cada vez que se llame a getFeatureInfo
    dojo.event.kwConnect({adviceType:"before", srcObj: gestorOperaciones, srcFunc: "getFeatureInfo", adviceObj: gestorComboFeatureInfo, adviceFunc: "setCapaYCamposFeatureInfoAlControlador", once:true});
    interactuadorConUsuario.init(bboxPeticion, chincheta);
}

function finVariablesGlobales(){
    CAPAS_PETICIONES_GEOPISTA = null;
    CAPAS_PETICIONES_SERVIDORES_EXTERNOS = null;
    peticiones = null;
    inicializaCapas = null;
    initObjetos = null;
    initIconos = null;
    initArriba = null;
    initCreaLeyendas = null;
    creaObjetoAMostrar = null;
    
    eligeMunicipio = null;
    obtenParametro = null;
    configuracionGetFeatureInfo = null;
    leyendasGeopista = null;
    leyendas = null;
    
    CAPAS_PETICIONES_SERVIDORES_EXTERNOS = null;
    CAPAS_PETICIONES_GEOPISTA = null;
}



function creaObjetoAMostrar(widthMapa, heightMapa, capaPadre){
    var barraProgreso;
    var funcCargando = null;
    var funcVisible = null;
    //if(!IE){
    var parametrosBarraProgreso = {id:"barraProgreso", width:(widthMapa/4), height:20, hasText:false};
    barraProgreso = dojo.widget.createWidget("ProgressBar", parametrosBarraProgreso);
    barraProgreso.domNode.style.top=((heightMapa-20)/2)+"px";
    barraProgreso.domNode.style.left=(widthMapa/3)+"px";
    barraProgreso.domNode.style.position="absolute";
    
    var mensaje = document.createElement("div");
    mensaje.align = "center";
    mensaje.innerHTML = "Cargando...";//CARGANDO_MAPA;
    mensaje.style.backgroundColor="#FFFFFF";
    mensaje.style.zIndex=220;
    barraProgreso.domNode.appendChild(mensaje); 
    
    barraProgreso.domNode.style.zIndex=200;
    barraProgreso.domNode.style.backgroundColor="#FFFFFF";
    
    funcCargando = "_objetoAMostrarMientrasSeCargaPeticion.startAnimation()";
    funcVisible= "_objetoAMostrarMientrasSeCargaPeticion.stopAnimation()";
    /*}else{
        barraProgreso = document.createElement("img");
        barraProgreso.src="img/progressbar.gif";   
    }*/    
    
    var _objetoAMostrarMientrasSeCargaPeticion = new GEOPISTA.Base.ObjetoAMostrarMientrasSeCargaPeticion(capaPadre);
    _objetoAMostrarMientrasSeCargaPeticion.setObjeto({objeto:barraProgreso, funcionCargando: funcCargando, funcionVisible:funcVisible});
    return _objetoAMostrarMientrasSeCargaPeticion;
    //gestorImagenesMapas.addObjetoAMostrarMientrasSeCargaPeticion(objetoBarraProgreso);
    
}
