﻿//var FlotanteHeight, FlotanteWidth;
var prm;
var layer;
var xmlFormado;

LtnWebViewer1.notifyLoad(onVisorloaded);
LtnWebViewer1.notifyError(onVisorError);

function load() {

    //para actualizar el visor despues de una peticion al servidor
   var prm = Sys.WebForms.PageRequestManager.getInstance();
   prm.add_initializeRequest(InitializeRequest);
   prm.add_endRequest(EndRequest);
}
var i;
function onVisorloaded()
{
    comprobarBloqueo(); 
    
    LtnWebViewer1.removeSystemBehavior(WVBehaviorType.UTMCOORDS);

    var beh = new MiComportamiento();
    beh.init(LtnWebViewer1);
    //i=setInterval(GetXML,500);
    //pido xml al webservice
     GetXML();       
     //LtnWebViewer1.FitView();                 
}


function onVisorError() { alert("onVisorError"); }

function clickPrueba()
{
    var img = document.createElement('IMG');
    img.style.width="20";
    img.style.height="20";
    img.src="images/interfaz/informacion.jpg";
    var layer = LtnWebViewer1.createCustomLayer("test");
    layer.addItem(img, LtnWebViewer1.getCenterUtmX(), LtnWebViewer1.getCenterUtmY());

}

function iconClick(id, layer, filepos)
{
    getIconOver(id, layer);
}
function iconOver(obj, id, layer, filepos)
{
    status = "OVER = "+id+" "+layer+" "+filepos;
}
function iconOut(obj, id, layer, filepos)
{
    status = "OUT = "+id+" "+layer+" "+filepos;
}

function seleccionar(ltnid)
{
    //SetCargando(true);
    var ret = WebService.SetLtnId(ltnid, OnCompleteseleccionar, OnErrorBuscar, OnErrorBuscar);
}

function OnCompleteseleccionar(arg)
{

    if(arg!=null && arg!="")
        LtnWebViewer1.refreshSystemLayer(WVLayerType.VECTOR);
    SetCargando(false);
}

function buscar(value)
{
    SetCargando(true);
    var ret = WebService.GetResults(value, OnCompleteBuscar, OnErrorBuscar, OnErrorBuscar);
   
}

function leerXML(text)
{
    var xmlDoc = null;
    try //Internet Explorer
      {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async="false";
      xmlDoc.loadXML(text);
      }
    catch(e)
      {
      xmlDoc = null;
      try //Firefox, Mozilla, Opera, etc.
        {
        parser=new DOMParser();
        xmlDoc=parser.parseFromString(text,"text/xml");
        }
      catch(e) {
        xmlDoc = null;
        alert("error leyendo xml: "+e.message)
        }
      }
      return xmlDoc;
}


function OnCompleteBuscar(arg)
{
   // alert("OnCompleteBuscar "+arg);
    var s = "";
    var xml = leerXML(arg);
    if (xml)
    {
        opt = xml.getElementsByTagName('salida');
        if(opt)
        {
            layer.clear();
            for(var i=0;i<opt.length;i++)
            {
                if(opt[i].firstChild)
                for(var j=0;j<opt[i].firstChild.childNodes.length;j++)
                {
                
                      var ic = opt[i].firstChild.childNodes[j].getAttribute('Icono');
                }
            }
            LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);
        }
    }
    GE("DR").innerHTML = "<table border='0'>"+s+"</table>";
    SetCargando(false);
}

function getIcono(o)
{
    var ic = o.getAttribute('Icono');
    return ((!ic)?"http://www.geonet.es/ibi/images/calle.gif" : "" + ic);
}

//function trans(name, o)
//{
//    var s="";
//    var x = o.getAttribute('x'); 
//    var y = o.getAttribute('y');
//    var ltnid = o.getAttribute('LtnId');
//    var minx = o.getAttribute('minx');
//    var href = o.getAttribute('oc');
// 
//    switch(name)
//    {
//        case "Poblaciones":
//            s += (minx && minx!="") ? ("<a href=\"javascript:goMinMax('" + minx + "#" + o.getAttribute('miny') + "#" + o.getAttribute('maxx') + "#" + o.getAttribute('maxy') + "'," + ((ltnid && ltnid!="") ? ltnid : "null") + ")\">" + o.getAttribute('titulo') + "</a>") : ""+o.getAttribute('titulo');
//            s += " ("+o.getAttribute('Muni')+")";
//            break;
//        case "PoblacionesCP":
//            s += (minx && minx!="") ? ("<a href=\"javascript:goMinMax('" + minx + "#" + o.getAttribute('miny') + "#" + o.getAttribute('maxx') + "#" + o.getAttribute('maxy') + "'," + ((ltnid && ltnid!="") ? ltnid : "null") + ")\">" + o.getAttribute('titulo') + "</a>") : ""+o.getAttribute('titulo');
//            s += " ("+o.getAttribute('Muni')+") CP:"+o.getAttribute('CodigoPostal');
//            break;
//        case "Tramos":
//            s += "<a href=\"javascript:goMinMaxLtnIds('" + getLtnIds(o) + "')\">" + o.getAttribute('titulo') + "</a> ("+o.getAttribute('Muni')+") CP:"+o.getAttribute('CodigoPostal');
//            break;
//        case "TramosLibres":
//            s += "<a href=\"javascript:goMinMaxLtnIds('" + getLtnIds(o) + "')\">" + o.getAttribute('titulo') + "</a> ("+o.getAttribute('Muni')+") CP:"+o.getAttribute('CodigoPostal');
//            break;
//        case "TramosExactos":
//            s += (minx && minx!="") ? ("<a href=\"javascript:goMinMax('" + minx + "#" + o.getAttribute('miny') + "#" + o.getAttribute('maxx') + "#" + o.getAttribute('maxy') + "'," + ((ltnid && ltnid!="") ? ltnid : "null") + ")\">" + o.getAttribute('titulo') + "</a>") : ""+o.getAttribute('titulo');
//            s += " ("+o.getAttribute('Muni')+") CP:"+o.getAttribute('CodigoPostal');
//            break;
//        case "resultados":
//            s += (x && x!="") ? ("<a href=\"javascript:goXYID(" + x + "," + y + ","+((ltnid && ltnid!="")?ltnid:"null")+")\">" + o.getAttribute('titulo') + "</a>" ) : ""+o.getAttribute('titulo');
//            s +=  " ("+o.getAttribute('NombreTipo')+")";
//            s += (href && href!="") ? " <img src='images/interfaz/informacion.jpg' style='cursor:pointer' title='Abrir ficha en ventana aparte' onclick='abrirVentana(\""+href+"\")' />" : "";
//            break;
//    }
//    
//    if(x && x!="" && y && y !="")
//    {
//        layer.addItem(nuevaFoto(getIcono(o), o.getAttribute('titulo'), o.getAttribute('oc')), x, y);
//    }
//    
//    return s;
//}

function getLtnIds(o)
{
    var ob, minx, miny, maxx, maxy;
    var mminx=999999999, mminy=9999999999, mmaxx=0, mmaxy=0;
    var s = "";
    for(var i=0;i<o.childNodes.length;i++)
    {
        ob = o.childNodes[i];
        minx = parseFloat(ob.getAttribute('minx'));
        miny = parseFloat(ob.getAttribute('miny'));
        maxx = parseFloat(ob.getAttribute('maxx'));
        maxy = parseFloat(ob.getAttribute('maxy'));
        if(minx<mminx) mminx = minx;
        if(miny<mminy) mminy = miny;
        if(maxx>mmaxx) mmaxx = maxx;
        if(maxy>mmaxy) mmaxy = maxy;
        s += parseFloat(ob.getAttribute('LtnId'))+";";
    }
    s += s.substr(0, s.length-1); //le quito el último ';'
    s += "|"+mminx+"#"+mminy+"#"+mmaxx+"#"+mmaxy;
    return s;    
}

function goMinMaxLtnIds(cad)
{
    var o = cad.split('|');
    if(o.length>1)
    {
        //alert(o[1]+"  --  "+o[0]);
        goMinMax(o[1], o[0]);
    }
}

function nuevaFoto(src, title, click)
{
    var img = document.createElement('IMG');
    //img.style.width="20";
    //img.style.height="20";
    img.src = (src)?src:"images/interfaz/informacion.jpg";
    img.title = ""+title;
    img.style.cursor = "pointer";
    img.onclick = function() { abrirVentana(click);} 
    return img;
}

function OnErrorBuscar(arg)
{
    alert("OnErrorBuscar arg="+arg._message);
    SetCargando(false);
}

function getIconOver(id, layer)
{
    SetCargando(true);
    var ret = WebService.GetDescription(id, layer, OnCompleteIcon1, OnErrorIcon1, OnErrorIcon2);
}

function OnCompleteIcon1(arg)
{
alert("OnCompleteIcon arg="+arg);
    /*if(iconOverCtrl)
    {
        if (arg=="") arg="Sin descripción";
        iconOverCtrl.alt=arg;
        iconProcessing=false;
    }*/
        SetCargando(false);
}

function OnErrorIcon1(arg)
{
alert("OnErrorIcon1 arg="+arg._message);
    //iconProcessing=false;
        SetCargando(false);
}

function OnErrorIcon2(arg)
{
alert("OnErrorIcon2 arg="+arg._message);
    //iconProcessing=false;
        SetCargando(false);
}

function tecla(e)
{
    if(esEnter(e))
        GE('btnBuscar').click();
}

function esEnter(e)
{
	var codigo=null;
	if(window.Event) 
	    codigo=e.which;
	else
	{
		if(e.type=="keypress") codigo=e.keyCode;
	}

	if (e.type=="keypress" && codigo==13)
		return true;
	return false;
}



function crearImgLink(src, desc, enlace)
{
    var img = document.createElement('IMG');
    img.style.width="20";
    img.style.height="20";
 
    img.src = src;
    img.title = desc;
    img.setAttribute("alt",desc);
    img.style.cursor = "pointer";
    if(enlace!="")
    img.onclick = function() { 
        try{
            jsImgLink(enlace);
        }
        catch(e){
           abrirVentana(enlace); 
        }  
    } 
       
    return img;
}

//para poner iconos recibidos por xml
function OnCompleteCargaIconosXml(arg)
{

    xmlFormado = leerXML(arg);
    var  punto_x;
    var  punto_y;
    var ancho=0;
    var img;
    var ico;
    var desc;
    var pin;
    var enlace;
   
    layer = LtnWebViewer1.createCustomLayer("iconos");
        
    if (xmlFormado)
    {
        opt = xmlFormado.getElementsByTagName('l');
        if(opt )
        {
            html = "<div style=\"width: 150px; height: "+((opt.lenght-1)*20)+"px;\">"; 
            //layer.clear();   
            for(var i=0;i<opt.length;i++) 
            {      
 
                if(opt[i].firstChild)
                {  
                    pin = opt[i].getAttribute('a');
                    html += "<image height=\"15\" width=\"15\" src=\""+opt[i].getAttribute("i")+"\" />";
                    
                    if(pin=="false")
                        html += "&nbsp;<input name=\"elementos_pint\" id=\"chk_"+i+"\" checked=\"1\" type=\"checkbox\" onclick=\"javascript:ActualizaCheck("+i+"); ActualizaIconos();\"";              
                    else    
                        html += "&nbsp;<input name=\"elementos_pint\" id=\"chk_"+i+"\" type=\"checkbox\" onclick=\"javascript:ActualizaCheck("+i+"); ActualizaIconos();\"";              
                
                    html+=" style=\"border:none;\" /><span class='tituloCheck'>"+opt[i].getAttribute("n")+"</span>";
                    html+="<br/>";
                    
                    for(var j=0;j<opt[i].childNodes.length;j++)
                    {
                      
                        if(pin=="false")
                        {
                             ancho = opt[i].childNodes[j].getAttribute('p'); 
                             ico = opt[i].getAttribute('i');
                             desc = opt[i].childNodes[j].getAttribute('n');
                             punto_x = opt[i].childNodes[j].getAttribute('x');
                             punto_y = opt[i].childNodes[j].getAttribute('y');
                             enlace = opt[i].childNodes[j].getAttribute('oc');
                             img = crearImgLink(ico, desc, enlace);

                             layer.addItem(img, punto_x,  punto_y); 
                        }   
                    }
                }  
            }
            html += "</div>";
            
            var cp =document.getElementById("div_capas");
            if(cp!=null) document.getElementById("div_capas").innerHTML = html;
            
            if(opt.length==1)
            {
                if(opt[0].childNodes.length==1)
                {
                     if(ancho==0)
                     {
                        ancho = opt[0].childNodes[0].getAttribute('p');
                        punto_x = opt[0].childNodes[0].getAttribute('x');
                        punto_y = opt[0].childNodes[0].getAttribute('y');
                     }
                     LtnWebViewer1.ZoomWin(punto_x-ancho/2, punto_y-ancho/2, ancho, ancho); 
                 }
            }
            //si se ha marcado un punto a mano prevalece sobre el punto del unico hijo 
            comprobarParametros();
                                         
            LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);
        }
    }
}

//para actualizar los check en firefox
function ActualizaCheck(ch)
{
    var pasoCheck = GE("chk_"+ch);
    var c = pasoCheck.getAttribute('checked');
    //compruebo navegador
    var browser=navigator.appName;

    //netscape
    if (browser=="Netscape")
    {
        if(c)
        {
            pasoCheck.setAttribute('checked', null);
        }
        else
        {
            pasoCheck.setAttribute('checked',true);
        }
    }

}
//para actualizar iconos recibidos por xml
function ActualizaIconos()
{
    var punto_x;
    var punto_y;
    var img;
    var ico;
    var desc;
    var enlace;
   
    if (xmlFormado)
    {
        opt = xmlFormado.getElementsByTagName('l');
        if(opt)
        {       
            layer.clear();
 
            html = "<div style=\"width: 150px; height: "+((opt.lenght-1)*20)+"px;\">"; 
           // var lista_elementos=document.getElementsByName("elementos_pint");
            for(var i=0;i<opt.length;i++) 
            {       
                if(opt[i].firstChild)
                {
                    var pasoCheck = GE("chk_"+i);
                   
                    check = pasoCheck.getAttribute('checked');
                     
                    html += "<image height=\"15\" width=\"15\" src=\""+opt[i].getAttribute("i")+"\" />";
                    html += "&nbsp;<input id=\"chk_"+i+"\" type=\"checkbox\" onclick=\"javascript:ActualizaCheck("+i+"); ActualizaIconos();\"";

                    if(check)
                        html+= " checked=\"1\""; 
                       
                    html+=" style=\"border:none;\" /><span class='tituloCheck'>"+opt[i].getAttribute("n")+"</span>";
                    html+="<br/>";
                    if(check)
                    {
                   
                        for(var j=0;j<opt[i].childNodes.length;j++)
                        {
                                 ico = opt[i].getAttribute('i');
                                 desc = opt[i].childNodes[j].getAttribute('n');
                                 punto_x = opt[i].childNodes[j].getAttribute('x');
                                 punto_y = opt[i].childNodes[j].getAttribute('y');
                                 enlace = opt[i].childNodes[j].getAttribute('oc');
                                 img = crearImgLink(ico, desc, enlace);
                                 layer.addItem(img, punto_x,  punto_y);     
                        }
                    }
                }  
            }
            html += "</div>";
            
            var cp =document.getElementById("div_capas");
            if(cp!=null) document.getElementById("div_capas").innerHTML = html;
                   
            comprobarParametros();
                          
            LtnWebViewer1.refreshSystemLayer(WVLayerType.ICON);      
        }
    }
 
}
//si le pasa un x e y por parametro pinta un icono en la coordenada
function comprobarParametros()
{
    var URL = location.href.split("?");
    var ancho ="1000000";//por defecto esto
	if (URL.length > 1)	{
		datos = URL[1].split("&");
		var punto_x=null;
		var punto_y=null;
		for(var i=0; i<datos.length; i++)
		{
	        punto = datos[i].split("=");
    	    
	        if(punto[0]=="x")
	            punto_x = punto[1];
	         else if(punto[0]=="y")
	            punto_y = punto[1]; 
	        if(punto[0]=="p") //ancho del mundo
	            ancho=punto[1];
       }
       if(punto_x!=null && punto_y!=null)
       { 
		ico = imagenIcono;// "http://www.costablanca.org/iconosmapa/default.gif";
        desc = "Punto Marcado";
        enlace="";
        
        img = crearImgLink(ico, desc,enlace);
        layer.addItem(img, punto_x,  punto_y);  
        }
        if(punto_x!=null && punto_y!=null)
        LtnWebViewer1.ZoomWin(punto_x-ancho/2, punto_y-ancho/2, ancho, ancho); 

	}   
}

//para poder marcar un punto en el mapa
function seleccionarPunto()
{
    abrirHerramientaClick2(LtnWebViewer1 , marcarPunto);
    
}


function marcarPunto(visor, x, y) 
{ 
   var dato=null;
   var v_dato=null;
   
   cerrarHerramientaClick(LtnWebViewer1, marcarPunto);
   var parametros = location.href.split("?");
   param_ur ="?x="+x+"&y="+y;
   
   if (parametros.length > 1)	{
		datos = parametros[1].split("&");
		
		for(var i=0; i<datos.length; i++)
		{
	        par = datos[i].split("=");
            if(par[0]!="x" && par[0]!="y")
	            param_ur+="&"+par[0]+"="+par[1];
       }
       
	}  
   
   var t = document.getElementById(textbox1); 
   if(t) t.value = x+'|'+y;
   var b = document.getElementById(Button1);
   
   //llamo al click del boton, y ya en el boton haces lo que quieras en el servidor
   if(b) b.click();
   
   try{
   
      zoomWinTransicion(x,y,1000000,500000);
      // manejadorCliente();
   
   }
   
   catch(e){}
}
   
/* armando */

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();
        
        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;
        
        //se desplaza poco a poco hasta el punto (lo situa en el centro)
        //intervalo=setInterval(aumentar,100);
        ponIcono();
}

var auxX=0,auxY=0, contador=0;
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) );
            LtnWebViewer1.refresh();  
         }else{
            if(esc<esc2)
                LtnWebViewer1.setScale(parseInt(esc+esc/3) );
         }
       // SetCargando(false);
        return;
    }
    LtnWebViewer1.Move(-dX,-dY);
    
        
}
/* fin armando */

function ponIcono()
{
   var t = document.getElementById(textbox1).value; 

   var xy = t.split("|");


	   if(xy[0]!=null && xy[1]!=null)
       { 
		    ico = imagenIcono, // "http://www.costablanca.org/iconosmapa/default.gif";
            desc = "Punto Marcado";
            enlace="";
            layer.clear();
            img = crearImgLink(ico, desc,enlace);
            layer.addItem(img, xy[0],  xy[1]);  
            //centramos el punto seleccionado
            LtnWebViewer1.ZoomWin(xy[0]-1000000/2, xy[1]-1000000/2, 1000000, 1000000); 
        }

	   
}