﻿var ie=document.all;
var nn6=document.getElementById&&!document.all;

var isdrag=false;
var x,y;
var left, top;
var dobj;
var eventSaved;
var status;


function boxIt(theLeft,theTop,theRight,theBottom) {
            xoffset=(document.all)?document.body.scrollLeft:window.pageXOffset;
            yoffset=(document.all)?document.body.scrollTop:window.pageYOffset;
            clipLayer("rect",theLeft+xoffset,theTop+yoffset,theRight+xoffset,theBottom+yoffset);
            showLayer("rect");
}

function clipLayer(name,left,top,right,bottom) {
    var lay = document.getElementById(name);
    var lay2 = document.getElementById("mapaimg");

    lay2left = parseInt(lay2.left+0); 
    lay2top = parseInt(lay2.top+0);
    lay2right = parseInt(lay2.right+0);
    lay2bottom = parseInt(lay2.bottom+0);

    lay.style.left = left<lay2left ? lay2left : left;
    lay.style.top = top<lay2top ? lay2top: top;
    lay.style.width = right>lay2right ? lay2right-left : right-left;
    lay.style.height = bottom>lay2bottom ? lay2bottom-top : bottom-top;
}

function showLayer(name) {
    document.getElementById(name).style.visibility = "visible";
}

function hideLayer(name) {
    document.getElementById(name).style.visibility = "hidden";
    movida = document.getElementById("rect");
    movida.style.left=0;
    movida.style.top=0;
    movida.style.width=0;
    movida.style.height=0;
}


function movemouse(e)
{
  var fobj = nn6 ? e.target : event.srcElement;
  if (fobj.id=="mapaimg"){
    if (labelAbierto==0){
        var etiqueta;
        etiqueta=document.getElementById("etiqueta");
        etiqueta.style.visibility="hidden";
        
        vueltaAEstadoAnterior();
    }
  }
 
  
  if (isdrag)
  {
        var fobj = nn6 ? e.target : event.srcElement;
        var rect = document.getElementById("rect");

        if (fobj.className == "dragme"){    
            xparc = nn6 ? e.clientX : event.clientX;
            yparc = nn6 ? e.clientY : event.clientY;
            dobj.style.left = tx + xparc - x;
            dobj.style.top  = ty + yparc - y;
        }
        else{
            if (fobj.className == "nodragme" ){ 
                    x = nn6 ? e.clientX : event.clientX;
                    y = nn6 ? e.clientY : event.clientY;
                    boxIt(Math.min(xini,x),Math.min(yini,y),Math.max(xini,x),Math.max(yini,y));
            }
            else{
                if (fobj.className == "zoom" ){
                    x = nn6 ? e.clientX : event.clientX;
                    y = nn6 ? e.clientY : event.clientY;
                }else{
                    if (fobj.className == "capturepoint" ){
                        x = nn6 ? e.clientX : event.clientX;
                        y = nn6 ? e.clientY : event.clientY;
                    } else{
                        ratonLevantao(eventSaved);
                    } 
                }
    
            }
        }
            return false;
    
  }
}


function selectmouse(e) 
{
  var fobj = nn6 ? e.target : event.srcElement;
 
  var topelement = nn6 ? "HTML" : "BODY";
  var rect = document.getElementById("rect");
  nn6 ? eventSaved = e : eventSaved = event;
  
  while (fobj.tagName != topelement && (fobj.className != "dragme" && fobj.className != "nodragme" && fobj.className != "zoom" && fobj.className != "capturepoint") )
  {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }
    

  if (fobj.className == "dragme" || fobj.className =="nodragme" || fobj.className=="zoom" || fobj.className=="capturepoint"){
	status=fobj.className;
    isdrag = true;
    dobj = fobj;
    tx = parseInt(dobj.style.left+0);
    ty = parseInt(dobj.style.top+0);
    x = nn6 ? e.clientX : event.clientX;
    y = nn6 ? e.clientY : event.clientY;
    xini=x;
    yini=y; 

    
    (document.all && !window.opera) ? buttonClicked=eventSaved.button : buttonClicked=eventSaved.which;

    if (buttonClicked=="1"){
		//si hago click sobre el mapa, desactivo el punto parpadeante.
		despuntualiza();
		
        if (labelAbierto==0){
            document.onmousemove=movemouse;
            document.onmouseup=ratonLevantao;
	    //if ((window.attachEvent) && (status!="none")) // IE
		//	fobj.attachEvent("onmouseout", ratonLevantao);
        }
        else{
            document.onmousemove=null;
            document.onmouseup=null;
	    //if (window.attachEvent) // IE
		//fobj.detachEvent("onmouseout", ratonLevantao);
            
        }
    }else{
        document.onmousemove=null;
        document.onmouseup=null;
	//if (window.attachEvent) // IE
		//fobj.detachEvent("onmouseout", ratonLevantao);
        
    }
    
    return false;
  }
  else{
    status="";
  }
}


function toDrag(){
    document.getElementById("mapaimg").className = "dragme";
    document.getElementById("buttonselected").className = "dragme";
	status="dragme";
	
	//le asigno la clase al puntito que parpadea de posicion central
	document.getElementById("marco").className=document.getElementById("buttonselected").className;
	document.getElementById("imagenMarco").className=document.getElementById("buttonselected").className;
	
    elementos=document.getElementsByTagName("area");
    for (i=0; i<elementos.length; i++){
        
        elementos[i].className="dragme";
    
    }
    document.getElementById("etiqueta").className="dragme";
     botoneraClick('pyr_mano','pyr_mano_gris');
}

function toShape(){
    document.getElementById("mapaimg").className = "nodragme";
    document.getElementById("buttonselected").className = "nodragme";
	status="nodragme";
    
	//le asigno la clase al puntito que parpadea de posicion central
	document.getElementById("marco").className=document.getElementById("buttonselected").className;
	document.getElementById("imagenMarco").className=document.getElementById("buttonselected").className;
	
    elementos=document.getElementsByTagName("area");
    for (i=0; i<elementos.length; i++){
        
        elementos[i].className="nodragme";
    
    }
    document.getElementById("etiqueta").className="nodragme";
    botoneraClick('pyr_zoommas','pyr_zoommas_gris');
}

function toZoomMore(){
    document.getElementById("mapaimg").className = "zoom";
    document.getElementById("buttonselected").className = "zoom";
	status="zoom";
	
	//le asigno la clase al puntito que parpadea de posicion central
	document.getElementById("marco").className=document.getElementById("buttonselected").className;
	document.getElementById("imagenMarco").className=document.getElementById("buttonselected").className;
	
    document.getElementById("zoom").value=2;
    
    elementos=document.getElementsByTagName("area");
    for (i=0; i<elementos.length; i++){
        
        elementos[i].className="zoom";
    
    }
    document.getElementById("etiqueta").className="zoom";
}

function toZoomLess(){
    document.getElementById("mapaimg").className = "zoom";
    document.getElementById("buttonselected").className = "zoom";
	status="zoom";
	
	//le asigno la clase al puntito que parpadea de posicion central
	document.getElementById("marco").className=document.getElementById("buttonselected").className;
	document.getElementById("imagenMarco").className=document.getElementById("buttonselected").className;
	
    document.getElementById("zoom").value=-2;
    
    elementos=document.getElementsByTagName("area");
    for (i=0; i<elementos.length; i++){
        
        elementos[i].className="zoom";
    
    }
    document.getElementById("etiqueta").className="zoom";
    botoneraClick('pyr_zoommenos','pyr_zoommenos_gris');
}

function capturePoint(tipoCaptura, origenPeticion) {

	if(origenPeticion != ''){
		asignarInputGlobal(origenPeticion);
		//----- ESTADISTICAS ---------------------------------------------------------------
		if(opcionBusqueda=="pyr1_origen") oEstadisticas.opcion = 'PTO';
		else if(opcionBusqueda=="pyr1_destino") oEstadisticas.opcion2 = 'PTO';
		else oEstadisticas.opcion = 'PTO';
		//TODO: AÑADIR PARAMETROS DE ESTADISTICAS EN ESTA FUNCION
		var peticionEstadisticas = "";
		if(oEstadisticas.herramienta!='CI'){
			peticionEstadisticas = "&herramienta="+oEstadisticas.herramienta+"&opcion="+oEstadisticas.opcion+"&opcion2="+oEstadisticas.opcion2+"&info="+oEstadisticas.info;
			oEstadisticas.setEstadisticas(peticionEstadisticas);
			oEstadisticas.reset();
		}
		//--------------------------------------------------------------------
	}

    document.getElementById("capturarpunto").value=tipoCaptura;
    document.getElementById("mapaimg").className = "capturepoint";
    document.getElementById("buttonselected").className = "capturepoint";
	status="capturepoint";
	
	//le asigno la clase al puntito que parpadea de posicion central
	document.getElementById("marco").className=document.getElementById("buttonselected").className;
	document.getElementById("imagenMarco").className=document.getElementById("buttonselected").className;
    
    elementos=document.getElementsByTagName("area");
    for (i=0; i<elementos.length; i++){
        
        elementos[i].className="capturepoint";
    
    }
    document.getElementById("etiqueta").className="capturepoint";
    
     if (tipoCaptura=="mas_info"){
     botoneraClick('pyr_info','pyr_info_gris');
    }else{
    
      if (tipoCaptura=="nota_plano"){
         botoneraClick('pyr_ptointeres','pyr_ptointeres_gris');
      }
    }
}

function ratonLevantao(e){  

  if (!nn6 && e==null){
	e=event;
  }

  var fobj = nn6 ? e.target : e.srcElement;
 
  var topelement = nn6 ? "HTML" : "BODY";
  var rect = document.getElementById("rect");
    	
  while (fobj.tagName != topelement && (fobj.className != "dragme" && fobj.className != "nodragme" && fobj.className != "zoom" && fobj.className != "capturepoint") )
  {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }
        
    
  isdrag=false;

  //alert(status)
  //if (fobj.className =="nodragme"){
  if (status =="nodragme"){

    var movida = document.getElementById("rect");
    var marco = document.getElementById("mapa");
    minimox=parseInt(movida.style.left)-parseInt(marco.style.left);
    minimoy=parseInt(movida.style.top)-parseInt(marco.style.top);
    maximox=minimox+parseInt(movida.style.width);
    maximoy=minimoy+parseInt(movida.style.height);
    hideLayer("rect");
    if (((maximox-minimox<10) && (maximoy-minimoy<10)) || isNaN(minimox) || isNaN(minimoy)){
        x = nn6 ? e.clientX : e.clientX;
        y = nn6 ? e.clientY : e.clientY;
        
        x=x-parseInt(marco.style.left)+((document.all)?document.body.scrollLeft:window.pageXOffset);
        y=y-parseInt(marco.style.top)+((document.all)?document.body.scrollTop:window.pageYOffset);
        
        generaOpcionesMapa(x, y, 2, "", "zoom");
    }
    else{
        generaOpcionesMapa(minimox, minimoy, maximox, maximoy, "rectangle");
    }
  }

  if (status == "dragme"){
    var marco = document.getElementById("mapaimg");
    var div = document.getElementById("mapa");


    centrox=parseInt(marco.width)/2;
    centroy=parseInt(marco.height)/2;
    

    movimientox=parseInt(marco.style.left);
    movimientoy=parseInt(marco.style.top);
    

    if ((Math.abs(movimientox)<10 && Math.abs(movimientoy)<10)|| isNaN(movimientox) || isNaN(movimientoy)){
        x = nn6 ? e.clientX : e.clientX;
        y = nn6 ? e.clientY : e.clientY;
        
        x=x-parseInt(div.style.left);
        y=y-parseInt(div.style.top);
                
    }
    else{
        x=centrox-movimientox;
        y=centroy-movimientoy;  
    }


    generaOpcionesMapa(x, y, 1, "", "zoom");
    
  }

  if (status == "zoom"){
    var marco = document.getElementById("mapaimg");
    var div = document.getElementById("mapa");

    centrox = nn6 ? e.clientX : e.clientX;
    centroy = nn6 ? e.clientY : e.clientY;
    
    centrox=centrox-parseInt(div.style.left)+((document.all)?document.body.scrollLeft:window.pageXOffset);
    centroy=centroy-parseInt(div.style.top)+((document.all)?document.body.scrollTop:window.pageYOffset);

    zum = parseInt(document.getElementById("zoom").value);

    generaOpcionesMapa(centrox, centroy, zum, "", "zoom");

  }
  
  if (status == "capturepoint") {
    marco = document.getElementById("mapa");
    x=x-parseInt(marco.style.left)+((document.all)?document.body.scrollLeft:window.pageXOffset);
    y=y-parseInt(marco.style.top)+((document.all)?document.body.scrollTop:window.pageYOffset);
    tipo = document.getElementById("capturarpunto").value;
    
	var nearestStreet="";
	
    if (tipo=="que_tengo_cerca"){
        document.getElementById("puntitoX").value=Pix2Geo(x, 0);
        document.getElementById("puntitoY").value=Pix2Geo(y, 1);
   		$('spanPincharEnElPlano').style.display="inline";
  		$('spanPincharEnElPlano').innerHTML='&nbsp;<input type="text" size="3" value="'+txtRadio[idioma]+'" title="'+txtRadio[idioma]+'" id="radius_TXT" onfocus=this.value="" />&nbsp;&nbsp;&nbsp;<input id="button" type="button" class="boton" value="'+butCentrarEnElPunto[idioma]+'" onclick="$(\'selectTodosPoi\').checked=\'true\'; selectTodosPoi(); findLugarInteresTXT(\'pyr3_origen_pincharEnElPlano\')" title="'+titleRealizaConsultaYCentraEnPlano[idioma]+'" /><br /><br /><span id="spanPincharEnElPlano2">'+descripcionPincharSobrePlano[idioma]+'</span>';
		
		ponerPunto(Pix2Geo(x, 0), Pix2Geo(y, 1));
		 capturePoint("mas_info", '');  
     }else if (tipo=="rutas_origen"){
		marcarTipoOrigenDestinoSeleccionado(5); 
        document.getElementById("origenX").value=Pix2Geo(x, 0);
        document.getElementById("origenY").value=Pix2Geo(y, 1);
	  	
		ponerPunto(Pix2Geo(x, 0), Pix2Geo(y, 1));
		
		//OBTENER NOMBRE DE LA CALLE MAS CERCANA AL PUNTO SELECCIONADO
		getNearestStreet(Pix2Geo(x, 0), Pix2Geo(y, 1), 'origenText', 'tabLugarOrigen');
		
	  	document.getElementById('origen_XV').src='../EMT/imagenes/origen_V.gif';
		document.getElementById('origen_XV').title= titleImagenOrigenSeleccionada[idioma];
		//alert(nearestStreet)
		//document.getElementById('origenText').value= txtPuntoSeleccionadoEnPlano[idioma];
		//document.getElementById('tabLugarOrigen').innerHTML= txtPuntoSeleccionadoEnPlano[idioma];
		setUserRoute();
		 capturePoint("mas_info", '');  
     }else if (tipo=="rutas_destino"){
		marcarTipoOrigenDestinoSeleccionado(5); 
        document.getElementById("destinoX").value=Pix2Geo(x, 0);
        document.getElementById("destinoY").value=Pix2Geo(y, 1);
        
		ponerPunto(Pix2Geo(x, 0), Pix2Geo(y, 1));
		
		//OBTENER NOMBRE DE LA CALLE MAS CERCANA AL PUNTO SELECCIONADO
		getNearestStreet(Pix2Geo(x, 0), Pix2Geo(y, 1), 'destinoText', 'tabLugarDestino');
		
	  	document.getElementById('destino_XV').src='../EMT/imagenes/destino_V.gif';
		document.getElementById('destino_XV').title= titleImagenDestinoSeleccionada[idioma];
		//document.getElementById('destinoText').value= txtPuntoSeleccionadoEnPlano[idioma];
		//document.getElementById('tabLugarDestino').innerHTML= txtPuntoSeleccionadoEnPlano[idioma];
		setUserRoute();
		 capturePoint("mas_info", '');  
     }else if (tipo=="mas_info"){
        if (labelAbierto==0){
		    
		      var tipo_moreInfo=document.getElementById("moreInfo_tipoInfo").value;
		      if (tipo_moreInfo=="STREET"){
		        		      document.getElementById("moreInfo_x").value=Pix2Geo(x,0);
		        		      document.getElementById("moreInfo_y").value=Pix2Geo(y,1);
		      }
		
				  getMoreInformation();
        }
     }else if (tipo=="nota_plano"){
        document.getElementById("xcapturada").value=Pix2Geo(x, 0);
        document.getElementById("ycapturada").value=Pix2Geo(y, 1);
		
		//si esta habierta la etiqueta de info, es pq estamos encima de un POI o PARADA, con lo que no permitiremos poner notas.
		if($("etiqueta").style.visibility=="hidden"){

			//si pinchamos en el mapa cuando ya esta abierto, no debe hacer nada.
			if($("div_nota_al_plano").style.visibility!="visible"){
				getNotas($('idUsuario').value);
				
				document.getElementById("nota_al_plano").value="";
				document.getElementById("div_nota_al_plano").style.visibility="visible";
				document.getElementById("nota_al_plano").focus();
			}
		}
     }
  }
 
  

}

function getMoreInformation(){
   var xmin=parseFloat(document.getElementById("moreInfo_x").value)-1;
   var ymin=parseFloat(document.getElementById("moreInfo_y").value)+1;
   var xmax=parseFloat(document.getElementById("moreInfo_x").value)+1;
   var ymax=parseFloat(document.getElementById("moreInfo_y").value)-1;

   
   var x=Geo2Pix(xmin+1,0);
   var y=Geo2Pix(ymin+1,1);
   
   var tipo=document.getElementById("moreInfo_tipoInfo").value;
   

    opciones='?sec=moreinfo&xmin='+xmin+'&ymin='+ymin+'&xmax='+xmax+'&ymax='+ymax+'&scale='+$('escala').value+'&idioma='+$('idioma').value+'&tipo='+tipo;

    moreInfo(opciones, x, y);
}


function encuadreUtils(opcion, id){
    
    //********* SET ************
    if(opcion=='set'){
        var idUsuario = document.getElementById("idUsuario").value;
        var nombre = document.getElementById("nombreEncuadre").value;
        var minx=document.getElementById("minx").value;
        var miny=document.getElementById("miny").value;
        var maxx=document.getElementById("maxx").value;
        var maxy=document.getElementById("maxy").value;
        
        document.getElementById("div_anadir_encuadre").style.visibility="hidden";
        
        opciones='?sec=encuadreUtils&idUsuario='+idUsuario+'&nombre='+nombre+'&minx='+minx+'&miny='+miny+'&maxx='+maxx+'&maxy='+maxy+'&option=set';
    }
    //********** DELETE **************
    else if(opcion=='delete'){
        var idUsuario = document.getElementById("idUsuario").value;
        opciones='?sec=encuadreUtils&idUsuario='+idUsuario+'&id='+id+'&option=delete';
    }
    //*************** GET *****************
    else if(opcion=='get'){
        var idUsuario = document.getElementById("idUsuario").value;
        opciones='?sec=encuadreUtils&idUsuario='+idUsuario+'&option=get';
    }

	var aleatorio = Math.random();
	new Ajax.Request(_URL_mapUtilsPetitions+opciones+"&nocache="+aleatorio,
	{
	    method:'get',
	    onSuccess: function(transport){
		    var response = transport.responseText || "no response text";
		    //alert("Success! \n\n" + response);
			
			var equisemeele = getXMLObject(response);

			encuadresXMLtoHTML(equisemeele);
			
			//cargamos las opciones avanzadas del usuario almacenadas en bd en los inputs.
			getOpcionesAvanzadas('mapa');
		},
	    onFailure: function(){ 
	        alert(txtErrorProcesandoPeticion[idioma]);
		}
		
	});
    
}

function cerrarAddEncuadre(){

    document.getElementById("div_anadir_encuadre").style.visibility="hidden";
}

function encuadresXMLtoHTML(xmldata){

    var num =xmldata.getElementsByTagName('numEncuadres').item(i).firstChild.data;

    //si no hay ningun encuadre, no mostramos nada
    if(num>0){
        html='<h3>'+txtEncuadresPersonalizados[idioma]+'</h3><ul id="listaEncuadres">';
    
        for(var i=0; i<num; i++){
            var nombre =xmldata.getElementsByTagName('nombre').item(i).firstChild.data;
            var id =xmldata.getElementsByTagName('id').item(i).firstChild.data;
            
            var node= xmldata.getElementsByTagName('point').item(i)
            var minx = parseFloat(node.attributes[0].nodeValue);
            var miny = parseFloat(node.attributes[1].nodeValue);
            var maxx = parseFloat(node.attributes[2].nodeValue);
            var maxy = parseFloat(node.attributes[3].nodeValue);
            
            html+='<li><a href="#ancla_pyr1" onclick="generaOpcionesMapa('+minx+', '+miny+', '+maxx+', '+maxy+', \'map\')" >'+nombre+'</a>&nbsp;&nbsp;<a href="#ancla_pyr1" onclick="if(confirm(\'¿Deseas eliminar este encuadre?\')){encuadreUtils(\'delete\', '+id+')}"><img src="../EMT/imagenes/papeleraA.gif" border="0" title="'+titleEliminar[idioma]+'" /></a></li>';
        }
        html+='</ul>';
    
        document.getElementById('encuadres_personales2').innerHTML= html;
    }
    else document.getElementById('encuadres_personales2').innerHTML= '';
}


function moveTo(directionx, directiony){
    var marco = document.getElementById("mapaimg");

    centrox=parseInt(marco.width+0)/2;
    centroy=parseInt(marco.height+0)/2;

    if(directionx=="left"){
        centrox=centrox-200;
    }
    if(directionx=="right"){
        centrox=centrox+200;
    }

    if(directiony=="up"){
        centroy=centroy-200;
    }
    if(directiony=="down"){
        centroy=centroy+200;
    }

    generaOpcionesMapa(centrox, centroy, 1, "", "zoom");
}



function generaOpcionesConCentro(){
    if (document.getElementById("extentMinx").value!=0){
        generaOpcionesMapa(document.getElementById("extentMinx").value, document.getElementById("extentMiny").value, document.getElementById("extentMaxx").value, document.getElementById("extentMaxy").value, "map");
    }
    else{
        generaOpcionesMapa(document.getElementById("minx").value, document.getElementById("miny").value, document.getElementById("maxx").value, document.getElementById("maxy").value, "map");
    }
}

function toZoomAll() {
    opciones="?sec=map"
    opciones=opciones+"&minx=720770";
    opciones=opciones+"&miny=4366870";
    opciones=opciones+"&maxx=730670";
    opciones=opciones+"&maxy=4380700";
    opciones=opciones+"&height="+document.getElementById("alto").value;
    opciones=opciones+"&width="+document.getElementById("ancho").value;

    carga_mapa(opciones, false);
}


function ocultar_botones(){

    document.getElementById("pyr_dcha_rosa").style.display="none";
    document.getElementById("pyr_dcha_gris").style.display="inline";
    document.getElementById("pyr_ortofoto").className="pyr_ortofoto_gris"
    document.getElementById("pyr_ortofoto_ocultar").className="pyr_ortofoto_ocultar_gris"
    document.getElementById("pyr_ortofoto2").className="pyr_ortofoto2_gris"
}

function mostrar_botones(){

    document.getElementById("pyr_dcha_rosa").style.display="inline";
    document.getElementById("pyr_dcha_gris").style.display="none";
    document.getElementById("pyr_ortofoto").className="pyr_ortofoto"
    document.getElementById("pyr_ortofoto_ocultar").className="pyr_ortofoto_ocultar"
    document.getElementById("pyr_ortofoto2").className="pyr_ortofoto2"
}


document.onmousedown=selectmouse;



