﻿///<reference path="jquery-1.3.2-vsdoc.js"  />

var prm;
var FlotanteHeight, FlotanteWidth;
var escalaIni = "";
var provincia = "";
var municipio = "";
var nombreMuni = "";
var listaX, listaY;
var xmlHttp;
var intervaloPaneles;
var beh;
var conveniado;
var idPoi;
var isPostBack;

function setupAjax() {
    $.ajaxSetup({ url: "Handler.ashx", type: "GET", global: "false", error: OnError, cache: false });
}

function actualizarFechaAceptacionLOPD(usu) {
    $.ajax({ data: "tipo=ActualizarFechaAceptacionLOPD&usu=" + usu });
}

function zoomOut() {    
    LtnWebViewer1.ZoomOut();
}

function zoomIn() {
    LtnWebViewer1.ZoomIn();
}

function onVisorloaded()
{
    LtnWebViewer1.subscribeEvent(WVEventType.CHANGE_SCALE, RepintarLineas);
    LtnWebViewer1.subscribeEvent(WVEventType.ICON_CLICK, IconClick);
    LtnWebViewer1.subscribeEvent(WVEventType.ICON_OVER, IconOver);
    LtnWebViewer1.removeSystemBehavior(WVBehaviorType.UTMCOORDS);    
    
    beh = new MiComportamiento();
    beh.init(LtnWebViewer1);
    LtnWebViewer1.addCustomBehavior(beh);
    capasVisor = LtnWebViewer1.getSystemLayers();

    if (gup('lite') != "true" && gup('lite') != "1")
        comprobarCookies();

    LtnWebViewer1.setVectorOpacity(true);//Para que entren las capas con fadein
    
    var x = gup('x');
    var y = gup('y');
    var es = gup('scale');
    var idFicha = gup('idFicha');
    
    //Guardamos el id del POI pasado por parametro para abrir la ficha cuando lo obtenga en asincrono
    idPoi = gup('idPoi');
    
    if (x != "" && y != "") {    
        x = parseFloat(x, 10) * 1000;
        y = (parseFloat(y, 10) * 1000) + 3000;
        LtnWebViewer1.locate(x, y);
        var suma = gup('suma');        
        if ((suma == "1" || suma == "true") & (conveniado == "false" || conveniado == "0"))
            MiPutTackSUMA(x, y);
        else if(suma != "1" && suma != "true")
            MiPutTack(x, y, "");
    }

    if (es != "") {
        es = parseFloat(es, 10) * 10;
        LtnWebViewer1.setScale(es);        
        escalaAnterior = es;
    }

    if (idFicha != "") {
        var url = "./Ficha.aspx?idFicha=" + idFicha + "&x=" + x + "&y=" + y;
        abrirVentanaFlotante(url);
    }  
        
    cambiarEnlace();
    intervaloPaneles = setInterval(ocultarPanelesServicios, 1000);    
    setInterval(VisorActual,5*60000);
    
    if(GE('EIEL')!=null)
        GE('EIEL').disabled='';//Lo hacemos para que no casque la aplicacion    
    
    document.body.onresize = function() {
        redimensionarPanelProveedores();
    };

    generarPuntos(LtnWebViewer1);
}

function RepintarLineas(id, layer, filepos) {
    if (recorridoX != null) {
        localX = LtnWebViewer1.worldToLocalCoordX(recorridoX[0] + (escalaAnterior - escala));
        localY = LtnWebViewer1.worldToLocalCoordY(recorridoY[0] + (escalaAnterior - escala));
        nuevoPunto(localX, localY , true);

        for (var i = 1; i < recorridoX.length; i++) {
            localX = LtnWebViewer1.worldToLocalCoordX(recorridoX[i] + (escalaAnterior - escala));
            localY = LtnWebViewer1.worldToLocalCoordY(recorridoY[i] + (escalaAnterior - escala));
            nuevoPunto(localX, localY );
        }
    }
    escalaAnterior = escala;
}

function generarPuntos(visor) {
    if (recorridoX == null || recorridoX.length == 0) {
        recorridoX = new Array();
        recorridoY = new Array();
    }

    for (var i = 0; i < listaX.length; i++) {
        recorridoX.push(listaX[i]);
        recorridoY.push(listaY[i]);
        localX = visor.worldToLocalCoordX(listaX[i]);
        localY = visor.worldToLocalCoordY(listaY[i]);
        nuevoPunto(localX - 3, localY);
    }
}

function comprobarCookies() {
    try {
        var t = leerCookie("transparencia_Cartografia_GEONET");

        if (t != "") {
            setOpacidadVector(t);
            var slider = $find('panelRedondeadoBaseCarto_SliderExtender1');
            slider.set_Value(t);
        }
    } catch (Err) { }     
}


function leerCookie(nombre) {
   var a = document.cookie.substring(document.cookie.indexOf(nombre + '=') + nombre.length + 1,document.cookie.length);
   if(a.indexOf(';') != -1)a = a.substring(0,a.indexOf(';'))
   return a; 
}


function redimensionarPanelProveedores() {
    if ((document.body.offsetHeight - 205) > 20 && (document.body.offsetWidth - 40) > 20) {
        GE('panelRedondeadoTematico_tematicaCuerpo').style.height = (document.body.offsetHeight - 195) + "px";
        var o = GE("panelRedondeadoFrame_iframeFicha").width = (document.body.offsetWidth - 20);
    }
}

function onVisorError(e) { window.status = e + "_" + new Date(); }

function cargado() {
    LtnWebViewer1.notifyLoad(onVisorloaded);
    //objCoordenadas = $get("CoordenadasCuerpo");
    objCoordenadas = GE("divCoordenadas");
    LtnWebViewer1.notifyError(onVisorError); 
    LtnWebViewer1.AttachMouseMove(mouseMove);
    LtnWebViewer1.AttachChangeScale(changeScale);
    LtnWebViewer1.AttachToolFinished(soltarHerramienta);       
    FlotanteHeight = parseInt(screen.height * 0.6, 10);    
    FlotanteWidth = parseInt(screen.width - 45, 10);

    setInterval(callVisitas, 2*60000);
    callVisitas();	
	
	//Apagamos botones de urbanismo
	SetVisible("LtnWVButtonUrbanismo",false);	
	
	if(gup( 'lite' )!="true" && gup( 'lite' )!="1"){
	    try{
	        window.moveTo(0,0);
            window.resizeTo(window.screen.width,screen.availHeight);
        }catch(Err){}
        redimensionarPanelProveedores();
    }

    //Inicializamos la variable para mostrar un POI pasado por parametro solo cuando se carga la pagina al inicio
    isPostBack = false;
    
}

function VisorActual(){
//Mantenemos el visor vivo
    LtnWebViewer1.ping(); 
    window.status="Ultima actualizacion : "+ new Date();
}

var ibi=false,ibiAux="",contIbi=0,Boolurbanismo=false;
function soltarHerramienta(x){

    
    if(ibi==true && contIbi>=1){
        LtnWebViewer1.unsubscribeEvent(WVEventType.LEFT_CLICK,buscarReferencia);//quitareferencia al evento click
        ibi=false;
        contIbi=0;
        
       }
    if(Boolurbanismo==true && contIbi>=1){
        LtnWebViewer1.unsubscribeEvent(WVEventType.LEFT_CLICK,buscarUrbanismo2);//quitareferencia al evento click
        Boolurbanismo=false;
        contIbi=0;
        
       }
    if(ibi==true || Boolurbanismo==true){
        contIbi++;
    }
}


function ocultarPanelesServicios() {
    var control = $find('panelRedondeadoTematico_ac1_AccordionExtender');
    if (control != null) {
        if (gup('eiel') == "true" || gup('eiel') == "1") {
            GE("EIEL").checked = "checked";
            GE("SERVICIOS").checked = "";
            cambiarServiciosEiel();
        }
        else {
            GE("EIEL").checked = "";
            GE("SERVICIOS").checked = "checked";
            cambiarServiciosEiel();
        }

        if (gup('medioambiente') != "true" && gup('medioambiente') != "1") {
            p = control.get_Pane(3);
            if (p != null) {
                p.content.style.display = "none";
                p.header.style.display = "none";
            }
        } else {
            if (GE("checkboxMedioAmbiente") != null)
                GE("checkboxMedioAmbiente").click();
        }

        if (gup('urbanismo') != "true" && gup('urbanismo') != "1") {
            p = control.get_Pane(2);
            if (p != null) {
                p.content.style.display = "none";
                p.header.style.display = "none";
            }
        } else {
            if (GE("checkboxUrbanismo") != null)
                GE("checkboxUrbanismo").click();
        }
    }
    else if (gup('eiel') == "true" || gup('eiel') == "1") {
        var obj = new Object();
        obj.checked = true;
        ActivarTodasCapasEiel(obj);
    }
    
  clearInterval(intervaloPaneles);	
}


function gup( name ){
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp ( regexS );
	var tmpURL = window.location.href;
	var results = regex.exec( tmpURL );
	if( results == null )
		return"";
	else
		return results[1];
}

var capasVisor=0;
function setOpacidadVector(num){
    if(capasVisor==0)return;
    
    var d0=capasVisor[1];
    d0=d0.getContainer();
    d0.style.opacity=parseFloat(num)/100;
    d0.style.filter="alpha(opacity="+parseFloat(num)+")";
    
    try{
    document.cookie="transparencia_Cartografia_GEONET = "+num+"; expires = 2 Dec 2015 23:59:59 GMT";
    }catch(err){}
}

var intervalOpacidad=0;
var opacidadRaster=100;
var opacidadRasterAux=100;

function setOpacidadRaster(){
    if(opacidadRasterAux==opacidadRaster && intervalOpacidad!=0) {
        clearInterval(intervalOpacidad);
        intervalOpacidad=0;
        return;
     }
    if(opacidadRasterAux<opacidadRaster)
        opacidadRasterAux+=10;
    else
        opacidadRasterAux-=10;
    
    if(capasVisor==0)return;
    
    var d0=capasVisor[0];
    d0=d0.getContainer();
    d0.style.opacity=parseFloat(opacidadRasterAux)/100;
    d0.style.filter="alpha(opacity="+parseFloat(opacidadRasterAux)+")";
    
}

function callVisitas(x,y) {
    $.ajax({ data: 'tipo=GetVisitas',
        success: function(json, status) {
            GE("usuariosMapa").innerHTML = json.usuarioMapa;
            GE("usuariosAplicacion").innerHTML = json.usuariosConectados;
            GE("visitasMapa").innerHTML = json.usuariosTotalesEnMapa;
            GE("visitasAplicacion").innerHTML = json.usuariosTotales;
        },
        dataType: 'json'
    });
    return true;
}

var numCapaAux=-1;
function abrirCapa(nombre,num){
    
    var i=0;
    var obj=GE(nombre+i);
    
    while(obj!=null){ 
       obj.style.display="none";
       i++;
       obj=GE(nombre+i);
       
    }
    
    if(num!=numCapaAux){
        obj=GE(nombre+num);
        obj.style.display="";
        numCapaAux=num;
    }else numCapaAux=-1;
    
}

function EndRequest(sender, args) {
    /*if (postBackElement.id == 'Panel1Trigger') {
            SetCargando(false);
    }*/
    //alert(sender._postBackSettings.panelID);
    //alert(sender._postBackSettings.sourceElement.id);
    var llamada = sender._postBackSettings.sourceElement.id;
    //alert("EndRequest "+llamada);
    if(llamada.indexOf("cblProveedores")>=0 )
    {
        LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);        
    }
    if(llamada.indexOf("btnRefrescar")>=0)
    {
        LtnWebViewer1.Refresh();        
    }
    //alert(args.get_response().get_xml());
    //alert(args.get_response().get_statusCode());

   if (args.get_error() != undefined)
   {
       var errorMessage = args.get_error().message;
       alert(errorMessage);
       //args.set_errorHandled(true);
   }
    SetCargando(false);
}

function abrirHerramientaClick(visor, cursor, clickHandler)
{
    visor.ReleaseService();
    visor.AttachLeftClick(clickHandler);
    //visor.UIVisible(false);
    visor.SetCursor(cursor);
    //visor.PanEnabled = false;
    visor.lockControllers();
    visor.ZoomWinEnabled = false;
    var k=GE("HerramientasContenedor");
    k.style.visibility="hidden";
    LtnWebViewer1.removeCustomBehavior(beh);
}

 var  layer2 = 0;
 var cap=0;
function MiPutTack(x,y,msg)
{    
    if(layer2==0){
        layer2 = LtnWebViewer1.createCustomLayer("test");
    }
    
    layer2.clear();
    var img = document.createElement('IMG');
    img.style.width="30";
    img.style.height="30";
    img.src="images/interfaz/indicat.gif";
    layer2.addItem(img, x, y);
    
    if(cap==0){
        cap=LtnWebViewer1.getCustomLayers();
        cap=cap[cap.length-1].getContainer();
        cap.style.zIndex="15";
    }
                   
}

function MiPutTackSUMA(b, c) {
    if (layer2 == 0) layer2 = LtnWebViewer1.createCustomLayer("test");
    layer2.clear();
    var a = document.createElement("IMG");
    a.style.width = "24";
    a.style.height = "24";
    a.src = "images/servicios/suma.png";
    layer2.addItem(a, b, c);
    if (cap == 0) {
        cap = LtnWebViewer1.getCustomLayers();
        cap = cap[cap.length - 1].getContainer();
        cap.style.zIndex = "15"
    }
}

function cerrarHerramientaClick(visor, clickHandler) {
    visor.DetachLeftClick(clickHandler);
    visor.ReleaseService();
    visor.unlockControllers();
    visor.ZoomWinEnabled = true;
    var k=GE("HerramientasContenedor");
    k.style.visibility="visible";
    
    beh = new MiComportamiento();
    beh.init(LtnWebViewer1);
    LtnWebViewer1.addCustomBehavior(beh);
    LtnWebViewer1.releaseBehavior();
}

var cad1,cad2;
function gotoReferenciaCatastral(val) {

    
    if(GE("IReferenciaC1").value!="" && GE("IReferenciaC2").value!=""){//Estamos en el caso que nos pasen las referencias catastrales

        var obj1 = GE("IReferenciaC1");
        var obj2 = GE("IReferenciaC2");
        cad1 = obj1.value;//cad1 y cad2 son variables globales
        cad2 = obj2.value;
        
        
        if(cad1.length<7 && cad2.length<7)
            alert("Las referencias no pueden ser menores de 7 digitos");
        else
            CalcularCoordenadasX();

        
    }else{
        alert("Se tienen que rellenar los dos campos");
    }

}


function CalcularCoordenadasX(){//Funcion que se le pasan las referencias catastrales y devuelve X e Y
    
    SetCargando(true);

    $.ajax({ data: 'tipo=pasarRCtoUTM&rc1=' + cad1 + '&rc2=' + cad2,
        success: function(text, status) {
            if (text != "") {
                var o = text.split('#');
                gotoXY(o[0], o[1], 20000, 20000);
                MiPutTack(o[0], o[1]);
            }
            else
                alert("No se ha encontrado ninguna coordenada para esa referencia");

            SetCargando(false);
        }, dataType: 'text'
    });
   
    return true;
}

function imprimir()
{
    var scale = LtnWebViewer1.getScale();    
    var auxX=  LtnWebViewer1.getCenterUtmX();
    var auxY=  LtnWebViewer1.getCenterUtmY();
    
    //var url = "imprimir.aspx?h="+h+"&w="+w+"&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&scale="+scale+"&titulo="+titulo+"&rutaImagen="+escape(rutaMapa);
    var url = "getimg.aspx?municipioIne=03-" + municipio + "&scale=" + parseInt(scale / 10) + "&x=" + parseInt(auxX / 1000) + "&y=" + parseInt(auxY / 1000) + "&width=680&height=960&imprimir=true";

    GE("enlaceImprimir").href = url;
    return true;
//    ventanaImpresion.focus();
//    ventanaImpresion.document.write(salida);	
}

function clickInfo(visor, x, y) 
{ 
    callIDFicha(x,y)
    cerrarHerramientaClick(visor, clickInfo);
}

function callIDFicha(x,y)
{
    SetCargando(true);

    var ret = WebService.GetIDFicha(x, y, OnCompleteIDFicha, OnError, null);
    return true;
}

var intervaloRefresco=0;
function OnCompleteIDFicha(arg)
{
    if(arg!="")
    {
    
    intervaloRefresco= setInterval(refrescarVectorial,1000);
    LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);
        abrirFicha(arg);
        
    }
    SetCargando(false);
}
function OnTimeOut(arg)
{
    SetCargando(false);
}
function OnError(XMLHttpRequest, textStatus, errorThrown) {
    SetCargando(false);
}

function refrescarVectorial(){

    if(intervaloRefresco!=0) {clearInterval(intervaloRefresco); intervaloRefresco=0;}
    LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
}

function getInfo()
{
    abrirHerramientaClick(LtnWebViewer1, "help", clickInfo);
}

var escala = 0;
var escalaAnterior = 0;
var objCoordenadas;
var cont=0;
var UTMx;
var UTMy;
var recorridoX, recorridoY;
var coorX;
var coorY;
function mouseMove(visor, x, y)
{   
    if(x!=coorX || y!=coorY){
        cont++;
        if( (cont%20) == 0 )
        {
            coorX=x;
            coorY=y;
	        var geo=utm2geo(30,Math.round(x/1000),Math.round(y/1000))
	        var utm=geo2utm(geo[0],geo[1])
	        var huso=30;
	        UTMx=Math.round(utm[1])
	        UTMy=Math.round(utm[2])

            var aux="<table border=0 cellspacing=0 cellpadding=1 align=center >";
             aux+="<tr><td>(LAT,LON)="+desgloseGeo(geo[0])+((geo[0]>0)?'N':'S')+', '+desgloseGeo(geo[1])+((geo[1]>0)?'E':'W')+"</td><td></td>";
             aux+="<td>(X,Y)="+parseInt(x/1000)+", "+parseInt(y/1000)+"</td><td></td></tr>";
             aux+="</table>";
	        objCoordenadas.innerHTML = aux;           	    
	          	    
	    }
	}
	
}

var urlaux=window.location.href;
urlaux=urlaux.split('/');

var url="";
for(var i=1; i<urlaux.length-1; i++)
    url+=urlaux[i]+"/";

var url_enlace;
function cambiarEnlace(){

   var obj= GE("enlace");
   var centroX=parseFloat(LtnWebViewer1.getCenterUtmX());
       centroX=parseInt(centroX/1000);
      var centroY=parseFloat(LtnWebViewer1.getCenterUtmY());
       centroY=parseInt(centroY/1000);
   var escala=parseInt(LtnWebViewer1.getScale()/10);

   var salidaEnlace = "";
   
   if (GE('EIEL') != null && GE('EIEL').checked) salidaEnlace += "&eiel=1";
   if (GE('checkboxUrbanismo') != null && GE('checkboxUrbanismo').checked) salidaEnlace += "&urbanismo=1";
   if (GE('checkboxMedioAmbiente') != null && GE('checkboxMedioAmbiente').checked) salidaEnlace += "&medioambiente=1";
   if(!GE('checkboxOrto').checked) salidaEnlace+="&orto=0";
   if(!GE('checkboxCallejero').checked) salidaEnlace+="&vect=0";
   
   var salida="http:/"+url+"callejero.aspx?municipioINE="+gup('municipioINE')+"&x="+centroX+"&y="+centroY+"&scale="+escala+salidaEnlace;

   obj.innerHTML = "Enlace: <a href='" + salida + "' target='_blank' style='color:black'>" + salida + "</a>";
   url_enlace = salida;
}


function changeScale(visor)
{
    escala = ((visor && visor.GetScale) ? visor.GetScale() : 0);//mm por cada pixel
    GE("textoESCALA").innerHTML = (escala * GE("tablaESCALA").offsetWidth / 1000) + " m";
        
    if(escala>1){ 
        if(escala<256){
            opacidadRaster=20;
            if(intervalOpacidad!=0) clearInterval(intervalOpacidad);
            intervalOpacidad=setInterval( setOpacidadRaster,20);
        }
        else{
            if(opacidadRasterAux!=100){
                opacidadRaster=100;
                if(intervalOpacidad!=0) clearInterval(intervalOpacidad);
                intervalOpacidad=setInterval( setOpacidadRaster,20);
           }
        }
        
        if(escala<128)
           LtnWebViewer1.setScale(128);
     }
}

function go(x,y,id)
{
    if(id==undefined || id==null || id=="")
        gotoXY(x,y);
    else
        callID(id);
}

function callID(id)
{
    SetCargando(true);
    var ret = WebService.GetXYofID(id, OnCompleteID, OnTimeOut, OnError, null);
    return true;
}

function OnCompleteID(arg)
{
    if(arg!="")
    {
        var coord = arg.split(",");
        gotoXY(coord[0],coord[1],coord[2],coord[3]);
    }
    else
        alert("No se ha podido localizar ese elemento.");
    SetCargando(false);
}

function gotoXY(x,y,ancho,alto)
{
    if(ancho<0 || alto<0 || ancho==null || alto==null || isNaN(alto))
    {
        var escala = 100000;
        var mescala = escala>>1;
        zoomWinTransicion(x-mescala, y-mescala, escala, escala); 
    }
    else
        zoomWinTransicion(parseFloat(x,10), parseFloat(y,10), ancho, alto);  

}

var dX,dY,numVeces=15, esc,esc2, cx, cy, intervalo;
function zoomWinTransicion(x,y,ancho,alto){
        
        SetCargando(true);
        var v=LtnWebViewer1;
        var porcionAncho=ancho/v.getWidth();
        var porcionAlto=alto/v.getHeight();
        esc=Math.max(porcionAncho, porcionAlto) ;
        esc2=v.getScale();
        anchoAuxiliar=ancho;
        cx=parseFloat(parseFloat(x,10)+ancho/2);
        cy=parseFloat(parseFloat(y,10)+alto/2);
        
        
        
        cx=v.worldToLocalCoordX(cx);
        cx=parseInt(cx-v.worldToLocalCoordX(v.getCenterUtmX()));
        
        cy=v.worldToLocalCoordY(cy);
        cy=parseInt(cy-v.worldToLocalCoordY(v.getCenterUtmY()));
        
        var dif=Math.abs(v.worldToLocalCoordX(v.getCenterUtmX())-Math.abs(cx));
        var dif2=Math.abs(v.worldToLocalCoordY(v.getCenterUtmY())-Math.abs(cy));
        if(dif>v.getWidth() || dif2>v.getHeight())
            numVeces=1;
        else numVeces=7;
        
        
        var vCenter = v.getCenterUtm();
            //posición central en píxels
        var pxCenter = v.transformWorldToLocal(vCenter.x, vCenter.y);
        dX = cx / numVeces;
        dY = cy / numVeces;
        
        v.Move(-(cx % numVeces),-(cy % numVeces));
        
        contador=0;
        
        
        intervalo=setInterval(aumentar,100);
}

var auxX=0,auxY=0, contador=0;
var anchoAuxiliar;
function aumentar(){
    contador++;
        
    if(contador>numVeces){
        clearInterval(intervalo);
        var k=parseInt(esc+esc/3);
        var h=esc2;
        if(numVeces==1){
            LtnWebViewer1.setScale(parseInt(esc+esc/3) );
            
         }else{
            if(LtnWebViewer1.getWidth()!=anchoAuxiliar)
                LtnWebViewer1.setScale(parseInt(esc+esc/3) );
         }
        SetCargando(false);
        return;
    }
    LtnWebViewer1.Move(-dX,-dY);
        
}

function ActivarTodasCapasEiel(arg) {
    var salir=false;
	var obj;
	for(var i=0; salir!=true; i++){
	    obj=GE("servicioEiel"+i);
	    
	    if(obj==null)
	        salir=true;
	    else{
	        obj.checked=arg.checked;
	        ActivarCapaEIEL(obj);
	        }
	}
	capasVisor = LtnWebViewer1.getSystemLayers();
}

function ActivarTodasCapaServicios(arg){
    var salir=false;
	var obj;
	for (var i = 0; salir != true; i++)
	{
	    obj = GE("servicio" + i);

	    if (obj == null)
	        salir=true;
	    else {
	        obj.checked=arg.checked;
	        ActivarCapa(obj);
	    }
	}
    capasVisor= LtnWebViewer1.getSystemLayers();
}

function ActivarCapaMedioAmbiente(arg){
      SetCargando(true);
      $.ajax({ data: 'tipo=SetCapaMedioAmbiente&capa=' + arg.getAttribute("capa") + '&activo=' + arg.checked,
          success: function(text, status) {
              if (text != "") {
                  LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
                  LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);
              }
              SetCargando(false);

          }, dataType: 'text'
      });   
    return;
}

function ActivarCapa(obj)
{
    SetCargando(true);
    
    if(obj.checked){
        
        if(capasIconos[obj.value]==null)
           capasIconos[obj.value] = LtnWebViewer1.createCustomLayer(obj.value);

       callCrearCapas(obj.name, obj.value);
       
    }else{
        if(capasIconos[obj.value]!=null)
            capasIconos[obj.value].clear();
        SetCargando(false);
    }
    return true;
}

function ActivarCapaEIEL(obj)
{
    SetCargando(true);
    
    if(obj.checked){
        
        if(capasIconos[obj.value]==null)
           capasIconos[obj.value] = LtnWebViewer1.createCustomLayer(obj.value);
           
            callCrearCapasEIEL(obj.name, obj.value);
       
    }else{
        if(capasIconos[obj.value]!=null)
            capasIconos[obj.value].clear();
        SetCargando(false);
    }
    return true;
}

function callCrearCapas(name, valor) {
    contadorPuntuales++;
    $.ajax({ data: 'tipo=cargarIconos&tipo2=' + encodeURIComponent(name) + '&valor=' + valor + '&tipoIcono=servicios',
        success: function(text, status) {
            OnCompleteActivarCapa(text);
        }, dataType: 'text'
    });   
}

function callCrearCapasEIEL(name, valor) {
    contadorPuntuales++;
    $.ajax({ data: 'tipo=cargarIconos&tipo2=' + encodeURIComponent(name) + '&valor=' + valor + '&tipoIcono=eiel',
        success: function(text, status) {
            OnCompleteActivarCapa(text);
        }, dataType: 'text'
    }); 
}

function OnCompleteActivarCapa(arg) {
    var x2, y2, link, imag;
    var valorAux = arg.split('#')[0];
    var tipoServicio = valorAux.split('|')[1];
    var valor = valorAux.split('|')[0];
    var aux = arg.split('#')[1];
    aux = aux.split('|');
    var aux2 = "";
    var img;
    var id2;
    var titulo = "help";
    var con = 100;    
    var ie6 = (navigator.appVersion.indexOf("MSIE 6.0") > 0) ? true : false;

    for (var i = 0; i < aux.length; i++) {
        if (aux[i] != "") {
            aux2 = aux[i].split('$');
            x2 = aux2[0];
            y2 = aux2[1];
            imag = aux2[2];
            link = aux2[3];
            //link="http://www.geonet.es"+link.replace("..","");
            titulo = aux2[4];
            id2 = aux2[5];
            img = document.createElement('IMG');
            img.title = titulo;
            img.setAttribute("posx", x2);
            img.setAttribute("posy", y2);
            img.setAttribute("identificador", id2);
            img.setAttribute("link", link);
            img.alt = titulo;
            if (tipoServicio == "servicios") {
                img.style.width = "32";
                img.style.height = "32";
                img.className = "iconosSERVICIOS";
                
                if (ie6)
                    imag = aux2[2].replace("png", "gif");

                img.onclick = function() { abrirVentanaFlotanteFicha(this.getAttribute("identificador"), this.getAttribute("posx"), this.getAttribute("posy")); }
                img.onmouseout = function() { this.style.width = "32"; this.style.height = "32"; this.style.cursor = "default"; }
                img.onmouseover = function() { this.style.width = "34"; this.style.height = "34"; this.style.cursor = "pointer"; }
            }
            else {
                img.style.width = "24";
                img.style.height = "24";
                img.className = "iconosEIEL";
                img.onclick = function() { abrirVentanaFlotante("http://www.geonet.es/eiel/detalle.aspx?fase=2009&id=" + this.getAttribute("link")); }
                img.onmouseout = function() { this.style.width = "24"; this.style.height = "24"; this.style.cursor = "default"; }
                img.onmouseover = function() { this.style.width = "26"; this.style.height = "26"; this.style.cursor = "pointer"; }
            }

            img.src = imag;            
            capasIconos[valor].addItem(img, x2, y2);

            //Comprobamos si se ejecuta cuando se carga la pagina para comprobar si sacamos la ventana de informacion de un POI
            if (!isPostBack && idPoi == id2) {
                var posX = parseFloat(x2);
                var posY = parseFloat(y2);
                LtnWebViewer1.locate(posX, posY);
                abrirVentanaFlotanteFicha(id2, posX, posY);
            }
            
        }
    }
    SetCargando(false);
   
    //Comprobamos si se ha pintado todos los puntuales para habilitar los botones del radioButton
    if (--contadorPuntuales == 0) {
        var BotonEiel = GE('EIEL');
        if (BotonEiel.disabled == true)
            BotonEiel.disabled = false;
        else
            GE('SERVICIOS').disabled = false;

        if (!isPostBack)
            isPostBack = true;        
    }
}

var cursorAnterior="";
var capasIconos = new Array();

function cambiarProveedor(obj)
{
    if(obj.name=="urbanismo"){//urbanismo
        cambiarApantallaUrbanismo(obj);
    }
    if(obj.name=="medioambiente"){//medioambiente
        cambiarApantallaMedioAmbiente(obj);
    }
    
    if(obj.name=="todos"){//cartografia
        if(obj.checked==false)
            bloquear(false);
        else
            bloquear(true);
    }
    
    callProveedor(obj.checked, obj.value);
}

function bloquear(arg){
   /* if(arg){
       GE("checkboxCallejero").disabled=''; 
       //GE("checkboxCallejero").checked='ckecked';
       GE("checkboxCartografia").disabled='' ; 
    }else{
       GE("checkboxCallejero").disabled='disabled' ; 
       GE("checkboxCartografia").disabled='disabled' ; 
   }*/
}

function abrirPanelServicios(){
       //var s= GE("Panel1");//ServiciosContenedor
       //var control= $find('panelRedondeadoTematico_ac1_AccordionExtender');
       //control.set_SelectedIndex(0);  
       GE("SERVICIOS").click();
}

function cambiarApantallaMedioAmbiente(obj){

    var s= GE("Panel1");//ServiciosContenedor
    var control= $find('panelRedondeadoTematico_ac1_AccordionExtender');
      
    if(obj.checked==true) {
      
      var p=control.get_Pane(3);  
      p.content.style.display = "";
      p.header.style.display = "";
      control.set_SelectedIndex(3);  
    }
    else{
       var p=control.get_Pane(3);  
       p.content.style.display = "none";
       p.header.style.display = "none";
      abrirPanelServicios();
    }
}

var contadorPuntuales;

function cambiarServiciosEiel() {

    if (GE('SERVICIOS').checked) {
        cambiarApantallaSERVICIOS(true);
        cambiarApantallaEIEL(false);
        ActivarTodasCapasEiel(GE('EIEL'));
        contadorPuntuales = 0;
        GE('EIEL').disabled = true;
        ActivarTodasCapaServicios(GE('SERVICIOS'));
    }
    else{
        cambiarApantallaEIEL(true);
        cambiarApantallaSERVICIOS(false);
        ActivarTodasCapaServicios(GE('SERVICIOS'));
        contadorPuntuales = 0;
        GE('SERVICIOS').disabled = true;
        ActivarTodasCapasEiel(GE('EIEL'));
    }
}

function cambiarApantallaSERVICIOS(obj){
    var s= GE("Panel1");//ServiciosContenedor
    var control= $find('panelRedondeadoTematico_ac1_AccordionExtender');
    var p=control.get_Pane(0);  
    
    if(obj!=true) {
       p.content.style.display = "none";
       p.header.style.display = "none";
     }else{
       p.content.style.display = "";
       p.header.style.display = "";
       control.set_SelectedIndex(0);  
     }
}

function cambiarApantallaEIEL(obj){
    var s= GE("Panel1");//ServiciosContenedor
    var control= $find('panelRedondeadoTematico_ac1_AccordionExtender');
    var p=control.get_Pane(1);  
    
    if(obj!=true) {
       p.content.style.display = "none";
       p.header.style.display = "none";
     }else{
       p.content.style.display = "";
       p.header.style.display = "";
       control.set_SelectedIndex(1);  
     }
}

function cambiarApantallaUrbanismo(obj){

    var s= GE("Panel1");//ServiciosContenedor
    var control= $find('panelRedondeadoTematico_ac1_AccordionExtender');
      
    if(obj.checked==true) {
    
      abrirVentanaFlotanteContenido(mensajeUrbanismo);
      
      SetVisible("panelRedondeadoLeyenda_tematica",true);
      SetVisible("LtnWVButtonUrbanismo",true);
      bloquear(false);
       
      var p=control.get_Pane(2); 
      if(p!=null){ 
        p.content.style.display = "";
        p.header.style.display = "";
        control.set_SelectedIndex(2);  
      }
      
      GE("provUrb0").checked=true;//para que se ponga a checked
      cambiarLeyenda(GE("provUrb0").getAttribute("leyenda"));
      
    }
    else{
       SetVisible("panelRedondeadoLeyenda_tematica",false);
       SetVisible("LtnWVButtonUrbanismo",false);
       bloquear(true);
       
       var p=control.get_Pane(2);  
       p.content.style.display = "none";
       p.header.style.display = "none";
       abrirPanelServicios(); 
    }
}

function cambiarUrbanismo(arg){
    var atributo=arg.getAttribute("leyenda");
    cambiarLeyenda(atributo);
    callUrbanismo(arg.value);
}

function callUrbanismo(arg){

    $.ajax({ data: 'tipo=cambiarUrbanismo&aux=' + arg,
        success: function(text, status) {
            if (text == "1") {
                LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
            } else {
                LtnWebViewer1.refreshSystemLayer(WVLayerType.RASTER);
            }
        }, dataType: 'text'
    });    
}

function OnCompleteUrbanismo(arg){
    if(arg=="1"){
        LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
    }else{
        LtnWebViewer1.refreshSystemLayer(WVLayerType.RASTER);
    }
}

var src="";
function cambiarLeyenda(obj)
{   
    if(obj!="")
    {
        var o=GE("imagenLeyenda");
        o.src =  obj;
    }
   
}


function callProveedor(active,proveedor)
{
    SetCargando(true);
    $.ajax({ data: 'tipo=SetProveedor&active=' + active + '&position=' + proveedor,
        success: function(text, status) {
            if (text != "") {
                var o = text.split('|');
                if (o.length > 1 && parseInt(o[1]) == 0)
                    LtnWebViewer1.refreshSystemLayer(WVLayerType.RASTER);
                else
                    LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);

                if (o[1] == "0+") LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR); //Caso de urbanismo con escaneado
                if (o[1] == "4") LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);
            }
            else
                alert("No se ha podido cargar el proveedor.");

            SetCargando(false);
        },
        dataType: 'text'
    });
    return true;
}

function SetActivo(obj, value)
{
    //obj.style.border = value?"solid 1px red":"solid 0px white";
    obj.style.backgroundColor= value?"#f4a998":"";
}

function SetCargando(activo)
{
    SetVisible("UpdateProgressPral", activo);
}

function SetVisible(id, visible)
{
    var o = GE(id);
    o.width = "300";
    o.style.display = visible?"block":"none";
    o.style.visibility = visible?"visible":"hidden";
    
    o = GE("capaP");
    if(id=="UpdateProgressPral" && visible==true){
        
        o.style.top ="50%";
        o.style.left = ((screen.width/2)-50);
        o.width = "300";
    }else{
        o.style.top ="10%";
        o.style.left = "1%";
        o.width = "undefined";
        
    }
}

function abrirCapaPdfs(num){
    var o=GE("capaPdf0");
    for(var i=0; o!=null; i++){
        o.style.display="none";
        o=GE("capaPdf"+i);
    }
    
    SetVisible("capaPdf"+num,true);
}

function CerrarCapaPdfs(num){
   
    SetVisible("capaPdf"+num,false);
}


function clickTack(visor, x, y) 
{ 
    visor.PutTack(x, y, "X="+x+" Y="+y);
    visor.ClearDrawingArea();
    visor.SetColorDrawing("yellow");
    visor.DrawLine(x, y, x+300000, y+200000);
    visor.DrawLine(x, y, x+100000, y-100000);
    alert('0');
    var lx = new Array();
    lx.push(x);
    lx.push(x+300000);
    lx.push(x+100000);
    lx.push(x);
    var ly = new Array();
    ly.push(y);
    ly.push(y+200000);
    ly.push(y+300000);
    ly.push(y);

}

var lstX,lstY,lstUTMX,lstUTMY;

var layer = 0; //crea capa personalizada
var painter=0;
var layerPunto=0;
function nuevoPunto(tx, ty, cerrar)
{

    if(layerPunto==0)  {
      layerPunto = LtnWebViewer1.createCustomLayer("canvas"+Math.random());
      
      layerPunto.setAutoClean(false); //gestionamos manualmente
      painter = LtnWebViewer1.createLayerPainter(layerPunto);
      painter.setColor("d30c0c"); //asigna color de brocha
      painter.setStroke(2); //asigna tamaño de brocha
    }

	if (lstX==null || lstX.length==0)
	{ 
		lstX = new Array();
		lstY = new Array();
	}
	lstX.push(tx);
	lstY.push(ty);
	
	var visor = LtnWebViewer1;

    if(area==false){//en el caso que estemos pintando areas no pintamos la linea
	var pos = lstX.length-1;
	if(pos>0)
	{
		if(!cerrar)
		{
			painter.drawLine(lstX[pos-1], lstY[pos-1],lstX[pos], lstY[pos]); //pinta linea
            painter.paint(); //muestra el resultado en la capa
		}
		else
		{
		    painter.clear();
	  }
	}
	}
	      
        
    painter.paint(); //muestra el resultado en la capa

}


var distAcumulada = 0;
function medirDistancias()
{
	var pos = lstUTMX.length-1;
	var dist = 0;
	if(pos>0)
		dist = calcularDistancia(lstUTMX[pos-1]/1000, lstUTMY[pos-1]/1000, lstUTMX[pos]/1000, lstUTMY[pos]/1000);

    //Estas variable las utilizamos para la funcion de medir distancia
    distanciaParcial=dist;
    distanciaTotal+= dist;
	
	distAcumulada += dist;
	distAcumulada = devolverDecimales(distAcumulada, 2);
	
	dist = devolverDecimales(dist, 2);
	GE("PerfilDistancia").innerHTML = ""+distAcumulada;//"Distancia parcial: "+dist+" m.<br>Distancia total: "+distAcumulada+" m.";
	GE("PerfilPuntos").innerHTML = ""+lstUTMX.length;
}

function reiniciarMediciones()
{
	if(painter!=0){
        painter.clear();
        layerPunto=0;        
    }
	distAcumulada = 0;
	lstX = null;
	lstUTMX = null;
	GE("PerfilDistancia").innerHTML = ""+distAcumulada+"";
	GE("PerfilPuntos").innerHTML = "0";
}

function calcularDistancia(fx, fy, tx, ty)
{
	var c1 = Math.pow(Math.abs(fx-tx), 2);
	var c2 = Math.pow(Math.abs(fy-ty), 2);
	var dist = Math.sqrt(c1+c2);
	return dist;
}

function getPerfil()
{
    abrirHerramientaClick(LtnWebViewer1, "crosshair", clickPerfil);
    reiniciarMediciones();
    SetVisible("panelRedondeadoPerfil_tematica", true);
}

function cerrarMedirDistancias(){
    reiniciarMedicionesDistancia();
    cerrarHerramientaClick(LtnWebViewer1, clickDistancia);
    SetVisible("panelRedondeadoDistancia_tematica", false);
}

function getDistancia()
{
    abrirHerramientaClick(LtnWebViewer1, "crosshair", clickDistancia);
    reiniciarMedicionesDistancia();
    SetVisible("panelRedondeadoDistancia_tematica", true);
}

function cerrarMedirArea(){
    reiniciarMedicionesDistancia();
    cerrarHerramientaClick(LtnWebViewer1, clickArea);
    if(painterArea!=0) painterArea.clear();
    SetVisible("panelRedondeadoArea_tematica", false);
    area=false;
    layerArea=0;
}

var area=false;
function getArea()
{
    area = true;
    abrirHerramientaClick(LtnWebViewer1, "crosshair", clickArea);
    reiniciarMedicionesDistancia();
    SetVisible("panelRedondeadoArea_tematica", true);
    
    GE("DivPerimetro").innerHTML = "0 m.";
	GE("DivArea").innerHTML = "0 m.";
	SetVisible("trespuntos",true);
}


var xArea;
var yArea;
function clickArea(visor, x, y) 
{ 
    

    if (lstUTMX==null || lstUTMX.length==0)
	{ 
		lstUTMX = new Array();
		lstUTMY = new Array();
		
	    xArea = new Array();
		yArea = new Array();
	}

    
	lstUTMX.push(x);
	lstUTMY.push(y);
    localX = visor.worldToLocalCoordX(x);
    localY = visor.worldToLocalCoordY(y);
    
    xArea.push(localX);
    yArea.push(localY);
    
    
    nuevoPunto(localX-3, localY);
    medirDistancias();
    
    if(lstUTMX.length>2){
        SetVisible("trespuntos",false);
        var resultado=calcularArea().split('#');
        GE("DivPerimetro").innerHTML = devolverDecimales(resultado[1],2) +" m.";
	    GE("DivArea").innerHTML = devolverDecimales(resultado[0],2)+" m².";
    	
	     pintarArea();
    }
}

var painterArea=0;
var layerArea=0
function pintarArea(){

    if(layerArea==0){
          layerArea = LtnWebViewer1.createCustomLayer("canvasArea"+Math.random());
          
          layerArea.setAutoClean(false); //gestionamos manualmente
          painterArea = LtnWebViewer1.createLayerPainter(layerArea);
          painterArea.setColor("f0e319"); //asigna color de brocha
          painterArea.setStroke(2); //asigna tamaño de brocha
          
          var layert= layerArea.getContainer();
          layert.style.opacity=0.7;
          layert.style.filter="alpha(opacity=70)";
     }
      
    if(painterArea!=0){
        painterArea.clear();
                
    }
    
    
    //xArea.push(auxX[0]);
    //yArea.push(auxY[0]);
    
    painterArea.fillPolygon(xArea, yArea);
   
    painterArea.paint();
    
    painter.clear();
    
    //quitamos los dos que hemos puesto ultimos para cerrar el poligono
    
    //xArea.pop();
    //yArea.pop();
}


function clickDistancia(visor, x, y) 
{ 

    if (lstUTMX==null || lstUTMX.length==0)
	{ 
		lstUTMX = new Array();
		lstUTMY = new Array();
	}

    
	lstUTMX.push(x);
	lstUTMY.push(y);
    localX = visor.worldToLocalCoordX(x);
    localY = visor.worldToLocalCoordY(y);
    
    nuevoPunto(localX-3, localY);
    medirDistancias();
    
    
    GE("DivDistanciaParcial").innerHTML = devolverDecimales(distanciaParcial,2)+" m.";
	GE("DivDistanciaTotal").innerHTML = devolverDecimales(distanciaTotal,2)+" m.";
    
    
}

var distanciaParcial=0;
var distanciaTotal=0;
function reiniciarMedicionesDistancia(){

     distanciaParcial=0;
     distanciaTotal=0;
    
    lstX = null;
	lstUTMX = null;
    
    if(painter!=0){
        painter.clear();
        layerPunto=0;        
    }

	GE("DivDistanciaParcial").innerHTML = "0 m.";
	GE("DivDistanciaTotal").innerHTML = "0 m.";

}


function calcularArea()
{
	var cad = "";
	if (lstUTMY.length>2){
		var i;
		var min_y;
		var Area1;
		var vert1_x;
		var vert1_y;
		var vert2_x;
		var vert2_y;
		
		lstUTMX.push(lstUTMX[0]); //aadimos el primer punto a la lista
		lstUTMY.push(lstUTMY[0]);
		
		if (lstUTMY.length>0)
			min_y = lstUTMY[0];
			
		for (i=1; i<lstUTMY.length; i++)
		{
			if (lstUTMY[i]<min_y)
				min_y = lstUTMY[i];
		}
		
		Area1 = 0.0;
		perimetro = 0.0;
		for (i=1; i<lstUTMY.length; i++){
			vert1_x = lstUTMX[i - 1]/1000;
			vert1_y = lstUTMY[i - 1]/1000;
			vert2_x = lstUTMX[i]/1000;
			vert2_y = lstUTMY[i]/1000;
			Area1 += ((vert1_x - vert2_x)*((vert1_y-min_y) + (vert2_y-min_y))) / 2.0;
			perimetro += calcularDistancia(vert1_x, vert1_y, vert2_x, vert2_y);
		}

		lstUTMX.pop(); //quitamos el punto de cierre
		lstUTMY.pop();
		
		var res = devolverDecimales(Math.abs(Area1), 2);
		cad = res;
	}
	else 
		cad = "0#0";

	//glb_spanInfo.innerHTML = cad;
	return cad+"#"+perimetro;
}


function showVisor()
{
    var id = "panelRedondeadoVisor_tematica";
    var o = GE(id);
    if(o.style.display=="none" || o.style.visibility=="hidden")
        SetVisible(id, true);
    else
        SetVisible(id, false);
}

function showEntrada()
{
    SetVisible("panelRedondeadoLocalizar_tematica", true);
}

function cancelar(id)
{
    SetVisible(id, false);
}

function setEntrada()
{
    var x = parseInt(GE("UTMX").value,10) * 1000;
    var y = parseInt(GE("UTMY").value,10) * 1000;
    if(!isNaN(x) && !isNaN(y)){
        LtnWebViewer1.Locate(x, y);
        MiPutTack(x,y,"");
        }
    else
       alert("Las coordenadas deben ser números positivos y estar expresadas en metros.");
}


    var minx;
    var miny;
    var maxx;
    var maxy;
    
function clickPerfil(visor, x, y) 
{ 
	if (lstUTMX==null || lstUTMX.length==0)
	{ 
		lstUTMX = new Array();
		lstUTMY = new Array();
	}

    
	lstUTMX.push(x);
	lstUTMY.push(y);
    localX = visor.worldToLocalCoordX(x);
    localY = visor.worldToLocalCoordY(y);

    
    nuevoPunto(localX-3, localY);
    medirDistancias();
    
}

function mostrarPerfil()
{
   callPerfil(lstUTMX,lstUTMY)
}
function cancelarPerfil()
{
    SetVisible("panelRedondeadoPerfil_tematica", false);
    reiniciarMediciones();
    cerrarHerramientaClick(LtnWebViewer1, clickPerfil);
    RepintarLineas();
}
function callPerfil(listaX,listaY)
{
    var listX, listY;
    
    if(listaX==null) {
        alert("Introduzca al menos un punto.");
        return;
    }
    else {
        listX = '';
        listY = '';
        for (var i = 0; i < listaX.length; i++) {
                listX += listaX[i] + "-";
                listY += listaY[i] + "-";
        }
    }
    SetCargando(true);
    minx= LtnWebViewer1.localToWorldCoordX(0);
    miny= LtnWebViewer1.localToWorldCoordY(0);
    
     maxx= LtnWebViewer1.localToWorldCoordX(LtnWebViewer1.getWidth());
     maxy= LtnWebViewer1.localToWorldCoordY(LtnWebViewer1.getHeight());
     var aux="";
     
     for(var i=0; i< listaX.length; i++){
        aux+=parseInt( parseFloat(listaX[i])/1000)+","+parseInt( parseFloat(listaY[i])/1000)+",";
     }

     $.ajax({ data: 'tipo=GetPerfil&listaX=' + listX + '&listaY=' + listY + '&width=' + (FlotanteWidth - 35) + '&height=' + FlotanteHeight + '&minx=' + minx + '&miny=' + miny + '&maxx=' + maxx + '&maxy=' + maxy,
         success: function(text, status) {
             if (text != "") {
                 if (text != "-1")
                     abrirVentanaFlotante("Perfil.aspx?" + text, true);
                 else
                     alert("No es posible sacar el perfil. La ruta se ha salido de los límites de la cartografía.");
             }
             SetCargando(false);
         }, dataType: 'text'
     }); 
    
    return true;
}

function gotoMinMax(val)
{
    var obj = GE(val);
    var cad = obj.value;
    if(cad!=null && cad!="")
    {
        var o = cad.split('#');
        var ancho = parseInt(o[2],10) - parseInt(o[1],10);
        var alto = parseInt(o[4],10) - parseInt(o[2],10);
        if(!isNaN(alto)) alto=10000;
        gotoXY(o[1], o[2], ancho, alto);
        MiPutTack(o[1], o[2],"")
    }
}

function clickCorreo(visor, x, y) 
{ 
    if (lstUTMX==null || lstUTMX.length==0)
	{ 
		lstUTMX = new Array();
		lstUTMY = new Array();
	}

    
	lstUTMX.push(x);
	lstUTMY.push(y);
    localX = visor.worldToLocalCoordX(x);
    localY = visor.worldToLocalCoordY(y);

    
    nuevoPunto(localX-3, localY);
}

function CancelarCorreo(){
    
    SetVisible("panelRedondeadoCorreo_tematica", false);
    SetVisible("HerramientasContenedor", true);
    if(painter!=0)
        painter.clear();
    cerrarHerramientaClick(LtnWebViewer1, clickCorreo);
}

function EnviarCorreo()
{
    reiniciarMediciones();
    abrirHerramientaClick(LtnWebViewer1, "crosshair", clickCorreo);   
    SetVisible("panelRedondeadoCorreo_tematica", true);
}
function AceptarCorreo(){

    cambiarEnlace();
    var para= GE("para").value;
    var msg = encodeURIComponent(GE("mensaje").value);
    var listaX = '';
    var listaY = '';
    
    if(para.search(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/ig)){
        alert("La cuenta de correo que ha introducido no es valida.");
        return;
    }
    
    SetCargando(true);
    if (lstUTMX == null) {
        lstUTMX = new Array(); 
        lstUTMY = new Array();
    }
    else {
        for (var i = 0; i < lstUTMX.length; i++) {
            listaX += lstUTMX[i] + "-";
            listaY += lstUTMY[i] + "-";
        }
    }

    $.ajax({ data: 'tipo=EnviarCorreo&ruta=' + url_enlace + '&para=' + para + '&msg=' + msg + '&listaX=' + listaX + '&listaY=' + listaY,
        success: function(text, status) {
            SetVisible("HerramientasContenedor", true);
            SetVisible("panelRedondeadoCorreo_tematica", false);

            if (painter != 0)
                painter.clear();

            cerrarHerramientaClick(LtnWebViewer1, clickCorreo);
            SetCargando(false);
            alert("El mensaje se ha enviado correctamente");

        }, dataType: 'text'
    }); 
}

function BuscarLtnID(id){
    $.ajax({ data: 'tipo=BuscarElementoMedioAmbiente&id=' + id,
        success: function(text, status) {
            if (text != "") {
                var o = text.split("#");
                var ancho = parseInt(o[2]) - parseInt(o[0]);
                var alto = parseInt(o[3]) - parseInt(o[1]);
                alto = parseInt(alto, 10);
                ancho = parseInt(ancho, 10);
                if (alto < 0 || alto == 0) alto = 10000;
                var centroX = parseInt(o[0]) + (parseInt(o[2]) - parseInt(o[0])) / 2;
                centroX = parseInt(centroX);
                var centroY = parseInt(o[1]) + (parseInt(o[3]) - parseInt(o[1])) / 2;
                centroY = parseInt(centroY);

                gotoXY(o[0], o[1], ancho, alto);

                LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
            }
        }, dataType: 'text'
    });    
}

function liberarVisor(){
    LtnWebViewer1.releaseBehavior();
}

var cursorInterval = 0;

function fincas() {   
    LtnWebViewer1.releaseBehavior();
    LtnWebViewer1.subscribeEvent(WVEventType.LEFT_CLICK, buscarReferencia);
    
    //Si aprieta el boton derecho del raton se deshabilita 
    LtnWebViewer1.subscribeEvent(WVEventType.RIGHT_CLICK,liberarVisor);
    ibi = true;
    cursorInterval = setInterval(cursorHelp, 100);   
}

function urbanismo2() {
    LtnWebViewer1.releaseBehavior();   
    LtnWebViewer1.subscribeEvent(WVEventType.LEFT_CLICK,buscarUrbanismo2); 
    
    //Si aprieta el boton derecho del raton se desabilita 
    LtnWebViewer1.subscribeEvent(WVEventType.RIGHT_CLICK,liberarVisor);
    Boolurbanismo = true;
    cursorInterval = setInterval(cursorHelp, 100);   
}

function cursorHelp(){
    LtnWebViewer1.setCursor("help");
    clearInterval(cursorInterval);
}

function buscarReferencia(visor, x, y) {
    MiPutTack(x, y, "");    
    abrirVentanaFlotante("MostrarIbi.aspx?x=" + x + "&y=" + y);
}

function buscarUrbanismo2(visor, x, y) {
    MiPutTack(x, y, "");
    if (GE("checkboxUrbanismo").checked == true) {
      $.ajax({ data: 'tipo=buscarUrbanismo&x=' + x + '&y=' + y,
          success: function(text, status) {
              if (text != "") {
                  LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
                  abrirVentanaFlotante(text);
              }
              else
                  alert("No se ha encontrado ningún documento asociado");
          }, dataType: 'text'
      });
    }
    else
      alert("Para usar este servicio ha de estar la capa de urbanismo activada");      
}
  
function ocultarLeyenda(obj,objImg){
    var pleyenda=GE(obj);
    if(pleyenda.style.display==''){
        pleyenda.style.display='none';
        GE(objImg).src="./images/interfaz/expand_black.jpg";
    } 
    else {
        pleyenda.style.display='';
        GE(objImg).src="./images/interfaz/collapse_black.jpg";
    }

}

function SetPuntuales(obj){
    
    if(!obj.checked){
        ActivarTodasCapaServicios(obj);
        ActivarTodasCapasEiel(obj);
    }
    
    var s=GE('SERVICIOS');
    var e=GE('EIEL');
    
    if(!obj.checked){
        s.disabled='disabled';
        e.disabled='disabled';
    }else{
        s.disabled='';
        e.disabled='';
    }
    
    if(obj.checked){
       if(s.checked) ActivarTodasCapaServicios(obj);
       if(e.checked) ActivarTodasCapasEiel(obj);
    }
}


function MiComportamiento()
{
    var enabled = true;
    var viewer = null; //puntero al visor manipulado
    this.getEnabled=function()
    {
        return enabled;
    }
    this.setEnabled=function(enable)
    {
       enabled = enable;
    }
    this.init=function(v)
    {
        viewer = v;
        //suscripción a dobleclick del visor
        viewer.subscribeEvent(WVEventType.DOUBLE_CLICK, onDoubleClick);
    }

    var dX, dY, gVisor;
    var cont = 0;
    var numVeces = 15;
    function onDoubleClick(visor, utmX, utmY)
    {
        if (enabled)
        {
            gVisor = visor;

            //posición central del visor en UTM
            var vCenter = visor.getCenterUtm();
            //posición central en píxels
            var pxCenter = visor.transformWorldToLocal(vCenter.x, vCenter.y);
            //posición de destino en píxels
            var px = visor.transformWorldToLocal(utmX, utmY);
            //desplaza la vista desde el centro al destino
            
            dX = (pxCenter.x - px.x) / numVeces;
            dY = (pxCenter.y - px.y) / numVeces;
            //visor.move(pxCenter.x - px.x, pxCenter.y - px.y);
        }
    }

    this.onUpdate=function(deltaTime)
    {
        //status=3;
        //Do nothing ;-)
            
        if(gVisor)
        {
            gVisor.move(dX, dY);
            cont++;
            if(cont>=numVeces)
            {
                gVisor.ZoomIn();
                gVisor = null;
                cont = 0;
            }
        }
    }
    
    this.dispose=function()
    {
        //elimina suscripción a evento
        viewer.unsubscribeEvent(WVEventType.DOUBLE_CLICK, onDoubleClick);
    }
}

function GetNumerosMunicipios() {
    var codigo = GE("Calles").value;
    var category = provincia + "-" + municipio;
    $.ajax({ data: 'tipo=GetNumerosMunicipios&codigo=' + codigo + '&category=' + category,
        success: function(json, status) {
            var ddl = document.getElementById('DropDownList2');
            var numeros = eval(json);
            var i = 1;
            while (ddl.options.length != 1) {
                ddl.remove(i);
            }

            if (numeros.length > 0)
                ddl.disabled = "";
            else
                ddl.disabled = "disabled";

            for (i = 0; i < numeros.length; i++) {
                ddl.options[i + 1] = new Option(numeros[i].ndp, numeros[i].coord);
            }
        }, dataType: 'json'
    }); 
}

