/*
    AUTOR: Manuel Martos Ruiz
    FECHA: 31/03/2008
    TITULO DOCUMENTO: maparuidos.js
    TIPO DOCUMENTO: Archivo JScript
    DESCRIPCIÓN DOCUMENTO: Funcionalidad completa para
    la pantalla de bienvenida de la aplicación mapa ruidos.
    MODIFICACIONES(Autor/fecha/descripcion):
    
        - Manuel Martos / 2 Abril 2008 / Abre la interfaz por extensión en lugar de capa,valor / BuscarCoordenadasExtension()
*/


dojo.require("dojo.parser");
dojo.require("dojox.gfx");

dojo.addOnLoad(function()
{
    /* Comprobamos si está instalado o no el Silverlight */        
    if(dojox.gfx.renderer != "svg")
    {
        if(Silverlight.isInstalled("1.0")) Iniciar();
        else
        {
            /* Obtenemos el Silverlight */
            dojo.byId("html_Cuerpo").innerHTML = "";        
            
            var p = document.createElement("p");
            var a = document.createElement("a");
            p.innerHTML = "Está ejecutando el navegador <i>Microsoft Internet Explorer</i> y no tiene instalado el plug-in "+
                          "de <b>Microsoft Silverlight</b>. Pulse sobre el siguiente enlace para instalarlo desde el sitio "+
                          "oficial de Microsoft y así poder continuar. Recuerde que una vez instalado el plug-in, tiene que "+
                          "reiniciar su navegador antes de proseguir.";
                          
            a.innerHTML = "<b><h2>Instalar Microsoft Silverlight</h2></b>";
            a.title = "Haga click aquí para Instalar Microsoft Silverlight";
            a.href = "http://www.microsoft.com/silverlight";
                          
            dojo.byId("html_Cuerpo").appendChild(p);
            dojo.byId("html_Cuerpo").appendChild(a);
        }
    }
    /* Llamamos a la función que Inicializa todo */
    else Iniciar();
})

function Iniciar()
{
    /* Detectamos el navegador */
    var texto = dojo.byId("html_NavegadorSoportado");
    
    if(dojo.isFF >= 2 || dojo.isMoz > 0)
    {
        texto.innerHTML = "100%";
        texto.style.background = "#7FFF00";
    }
    if(dojo.isOpera >= 9)
    {
        texto.innerHTML = "95%";
        texto.style.background = "orange";
    }
    if(dojo.isIE == 6)
    {
        texto.innerHTML = "60%";
        texto.style.background = "orange";
    }
    if(dojo.isIE > 6)
    {
        texto.innerHTML = "95%";
        texto.style.background = "orange";
    }
    if(dojo.isSafari > 0 || dojo.isKhtml > 0)
    {
        texto.innerHTML = "???";
        texto.style.background = "red";
    }
    
    /* Iniciamos la sesión */
    IniciarSesion();
}

/* Inicia una nueva sesión */
function IniciarSesion()
{
    dojo.xhrGet({
        url: G_SIM_PATH + "AbreSesionMapa?contexto=MAPA DE RUIDOS",
        handleAs: "xml",
        timeout: G_EXPIRE_TIME,
        sync: false,
        handle: function(response, ioArgs)
        {        
            /* Procesamos el Error */
            if(response instanceof Error) MostrarError(response);
     
            /* No ha habido error, continuamos */
            else
            {
                var error = response.getElementsByTagName("error")[0].firstChild.nodeValue;
                
                if(error == "none")
                {
                    /* Almacenamos el identificador de sesión */
                    G_ID_SESION = response.getElementsByTagName("idmapasesion")[0].firstChild.nodeValue;
                    
                    /* Habilitamos los controles bloqueados */
                    dojo.byId("html_TxtBuscador").removeAttribute("disabled");
                    dojo.byId("html_BtnBuscar").removeAttribute("disabled");
                    
                    /* Agregamos el evento click al txtBox para borrar su contenido */
                    dojo.connect(dojo.byId("html_TxtBuscador"), "onfocus", function(evt){if(dojo.byId("html_TxtBuscador").value == "introduzca un texto a buscar") dojo.byId("html_TxtBuscador").value = "";});
                    
                    /* Agregamos el evento click al botón */
                    dojo.connect(dojo.byId("html_BtnBuscar"), "click", function(evt)
                    {   
                        var txt = dojo.trim(dojo.byId("html_TxtBuscador").value);                        
                        if(txt != "") RealizarBusqueda();
                    });
                    
                    /* Agregamos el evento ENTER sobre el txtBox (igual que click de botón) */
                    dojo.connect(dojo.byId("html_TxtBuscador"), "onkeydown", function(e){if(e.keyCode == 13){var txt = dojo.trim(dojo.byId("html_TxtBuscador").value);if(txt != "") RealizarBusqueda();}});
                    
                    /* Enviamos la versión del navegador al servicio web */
                    EnviarNavegador();
                    
                    /* Ocultamos el texto de Cargando... */
                    dojo.byId("html_Cargando").style.display = "none";
                }
                else MostrarError(error);
            }
        }
    }); 
}

/* Aborta la ejecución y muestra el mensaje de error */
function MostrarError(error)
{
    /* La petición ha sido cancelada por otro código JavaScript */
    if(error.dojoType == "cancel") alert('Se produjo el siguiente Error: \n \n' + "Petición Cancelada");

    /* Expiró el tiempo de la petición (timeout) */
    else if(error.dojoType == "timeout") alert('Se produjo el siguiente Error: \n \n' + "Expiró el tiempo dedicado a la petición");  

    /* Cualquier otro error */
    else alert('Se produjo el siguiente Error: \n \n' + error);
    
    /* Ocultamos el texto de Cargando... */
    dojo.byId("html_Cargando").style.display = "none";
}

/* Envía un mensaje al Servicio Web con la información del navegador */
function EnviarNavegador()
{
    var texto = ' Nombre: '+navigator.appName+
                ' | Version: '+navigator.appVersion+
                ' | Idioma: '+navigator.language+
                ' | Plataforma: '+navigator.platform+
                ' | Informacion_Adicional: '+navigator.userAgent;
    
    if(!Silverlight.isInstalled("1.0")) texto += " | NO SILVERLIGHT";
                
    dojo.xhrGet({
        url: G_SIM_PATH + "EnviarMensaje?idmapasesion="+G_ID_SESION+"&tipo=NAVEGADOR&texto="+texto,
        handleAs: "xml",
        timeout: G_EXPIRE_TIME,
        sync: false,
        preventCache: true
    });
}

/* Realiza la búsqueda */
function RealizarBusqueda()
{
    var valor = dojo.trim(dojo.byId("html_TxtBuscador").value);
    var capa = "CALLES";
    
    /* Comprobamos que se haya introducido algún valor */
    if(valor == "") MostrarError("Se ha de especificar un número mayor de caracteres para la búsqueda");
    else
    {
        /* Mostramos el texto de Cargando... */
        dojo.byId("html_Cargando").style.display = "";
                    
        /* Realizamos una conversión para el carácter Ñ */
        valor = valor.replace("ñ","%F1").replace("Ñ","%D1");
                
        dojo.xhrGet({
        url: (G_SIM_PATH + "BuscarToponimosPorValor?idmapasesion=" + G_ID_SESION + "&capa=" + capa + "&valor=" + valor + "&condicion=AND"),
        handleAs: "xml",
        headers: {"Content-Type": "text/xml; charset=ISO-8859-1"},
        timeout: G_EXPIRE_TIME,
        sync: false,
        handle: function(response, ioArgs)
        {      
            /* Procesamos el Error */
            if(response instanceof Error) MostrarError(response);

            /* No ha habido error, continuamos */
            else
            {
                var error = response.getElementsByTagName("error")[0].firstChild.nodeValue;
            
                /* Si no hay error */
                if(error == "none")
                {
                    /* Controlamos el máximo */
                    if(response.getElementsByTagName("toponimos").length > 0)
                    {
                        var maximo = response.getElementsByTagName("toponimos")[0].getAttribute("maximo");
                        
                        if(maximo == "none")
                        {                
                            var datos = response.getElementsByTagName("toponimo");
                            
                            /* Comprobamos que haya datos (lista no vacía) */
                            if(datos.length > 0)
                            {
                                var div = document.createElement("div");
                                div.style.height="100%";
                                div.style.width="100%";
                                var ul = document.createElement("ul");
                
                                /* Aplicamos estilos según el navegador */
                                if(dojo.isIE)
                                {
                                    ul.style.cursor = "hand";
                                    ul.style.fontFamily = "Arial";
                                    ul.style.fontSize = "11px";
                                }
                                else ul.setAttribute("style", "font-family: Arial; font-size: 11px; cursor: pointer;"); 
                                
                                for(var i=0; i<datos.length; i++)
                                {
                                    var li = document.createElement("li");            
                                    var texto = document.createTextNode(datos[i].getAttribute("valor"));
                                    dojo.connect(li, "onclick", function(evt){                                                              
                                        BuscarCoordenadasExtension(evt.target.getAttribute("capa"), evt.target.firstChild.nodeValue);                         
                                    });
                                    li.setAttribute("capa", capa);
                                    li.appendChild(texto);
                                    ul.appendChild(li);
                                }        
                                
                                /* Generamos los resultados visualmente */
                                dojo.byId("html_Resultados").innerHTML = "";
                                div.appendChild(ul);
                                dojo.byId("html_Resultados").appendChild(div);
                                
                                /* Ocultamos el texto de Cargando... */
                                dojo.byId("html_Cargando").style.display = "none";
                            }
                            else MostrarError("La búsqueda especificada no contiene resultados");
                        }                        
                        else MostrarError("La búsqueda contiene más de " + maximo + " resultados.\nSe ha de especificar un número mayor de caracteres para la búsqueda");
                    }
                    else MostrarError("La búsqueda especificada no contiene resultados");
                }
                else MostrarError(error);                        
            }
        }
      });
    }
}

/* Localiza las coordenadas de la extensión del elemento */
function BuscarCoordenadasExtension(capa, valor)
{
    /* Mostramos el texto de Cargando... */
    dojo.byId("html_Cargando").style.display = "";
        
    dojo.xhrGet({
    url: (G_SIM_PATH + "BuscarEntidadPorToponimo?idmapasesion=" + G_ID_SESION + "&capa=" + capa + "&valor=" + valor),
    handleAs: "xml",
    headers: {"Content-Type": "text/xml; charset=ISO-8859-1"},
    timeout: G_EXPIRE_TIME,
    sync: false,
    handle: function(response, ioArgs)
    {      
        /* Procesamos el Error */
        if(response instanceof Error) MostrarError(response);

        /* No ha habido error, continuamos */
        else
        {
            var error = response.getElementsByTagName("error")[0].firstChild.nodeValue;
        
            /* Si no hay error */
            if(error == "none")
            {
                var ext = response.getElementsByTagName("extension")[0];                
            
                /* Cargamos el mapa */
                AbrirVisorWeb(ext.getAttribute("xmin"), ext.getAttribute("ymin"), ext.getAttribute("xmax"), ext.getAttribute("ymax"));
                
                /* Ocultamos el texto de Cargando... */
                dojo.byId("html_Cargando").style.display = "none";
            }
        }
    }});
}

/* Abre la ventana emergente del visorweb */
function AbrirVisorWeb(x1,y1,x2,y2)
{
    var url = ("../index.html?x1="+x1+"&y1="+y1+"&x2="+x2+"&y2="+y2+"&contexto=Mapa de Ruidos").replace("ñ","%F1").replace("Ñ","%D1");
    var especificaciones="top=0, left=0, toolbar=no,location=no, status=yes, menubar=true, scrollbars=no, resizable=true";
  
    /* Abrimos la ventana con el mapa */
    window.open(url,"", especificaciones);
}
