var usuario="";
function Comprobar_Usuario()
{
	var login=document.getElementById("login").value;
var pass=document.getElementById("pass").value;
var url="Funciones_BD.php";
var data="login="+login+"&pass"+pass;
//**********************************************
 var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("POST", url); 
    XMLHttpRequestObject.setRequestHeader('Content-Type', 
      'application/x-www-form-urlencoded'); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) 
        {
          //callback(XMLHttpRequestObject.responseText); 
        //  document.getElementById(nombrediv).innerHTML = XMLHttpRequestObject.responseText;
        alert(XMLHttpRequestObject.responseText);
			if(XMLHttpRequestObject.responseText=="ok")
			{
				window.location.href='Bandeja_De_Entrada.php?login='+login;
				
				
			}
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
        } 
    }

    XMLHttpRequestObject.send(data); 
  }
//******************************************************
}
// Documento JavaScript
// Esta función cargará las paginas
var sitio_actual="";
var derecho_actual="";
function llamarasincrono(url, id_contenedor)
{
	
	//var oXMLHttpRequest = new XMLHttpRequest();
	var pagina_requerida = false
	if (window.XMLHttpRequest) 
	{// Si es Mozilla, Safari etc
		pagina_requerida = new XMLHttpRequest()
	} 
	else if (window.ActiveXObject)
	{ // pero si es IE
		try 
		{
				pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e)
		{ // en caso que sea una versión antigua
			try
			{
				pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false

	/*El atributo onreadystatechange
	 asigna la función que se ejecutará cada vez que readyState cambie 
	 de valor. 
	*/
	
	/* Se utiliza para definir una función para leer los datos recibidos del servidor,
	en este caso en su interior comprobaríamos que readyState tenga valor 4 y entonces 
	leeremos el valor de responseXML, responseText... 
	*/
	pagina_requerida.onreadystatechange=function()	{ // función de respuesta
		cargarpagina(pagina_requerida, id_contenedor)
	}
    var aleatorio=Math.random(); 
	
	if(url.indexOf("?")=="-1")
    {
    	
    	pagina_requerida.open('GET', url+"?nocache="+aleatorio, true) // asignamos los métodos open y send
	
    }
    else
    {
    	
    	
    	pagina_requerida.open('GET', url+"&nocache="+aleatorio, true) // asignamos los métodos open y send
	
    }
	//pagina_requerida.open('GET',url,true);
	pagina_requerida.send(null)
	//alert ( pagina_requerida.readyState );
}
// todo es correcto y ha llegado el momento de poner la información requerida
// en su sitio en la pagina xhtml
function cargarpagina(pagina_requerida, id_contenedor)
{
	if(pagina_requerida.readyState==1||pagina_requerida.readyState==2||pagina_requerida.readyState==3)
	{
	document.getElementById("cargando").style.visibility = "visible";
		if(id_contenedor=="contenidoMensaje")
		{
			
			document.getElementById("contenidoMensaje").innerHTML = "<img src=img/indicator_flower.gif> Cargando...";
		}
	
	}else if (pagina_requerida.readyState == 4 && (pagina_requerida.status==200 || window.location.href.indexOf("http")==-1))
	{
		document.getElementById("cargando").style.visibility = "hidden";
	//alert(pagina_requerida.responseText);
	document.getElementById(id_contenedor).innerHTML=pagina_requerida.responseText;
	}
}
///////////////////////////////
////////////////////////////////
function llamarasincronoXML(url, id_contenedor)
{
	
	//var oXMLHttpRequest = new XMLHttpRequest();
	var pagina_requerida = false
	if (window.XMLHttpRequest) 
	{// Si es Mozilla, Safari etc
		pagina_requerida = new XMLHttpRequest()
	} 
	else if (window.ActiveXObject)
	{ // pero si es IE
		try 
		{
				pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e)
		{ // en caso que sea una versión antigua
			try
			{
				pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false

	/*El atributo onreadystatechange
	 asigna la función que se ejecutará cada vez que readyState cambie 
	 de valor. 
	*/
	
	/* Se utiliza para definir una función para leer los datos recibidos del servidor,
	en este caso en su interior comprobaríamos que readyState tenga valor 4 y entonces 
	leeremos el valor de responseXML, responseText... 
	*/
	pagina_requerida.onreadystatechange=function()	{ // función de respuesta
		cargarpaginaXML(pagina_requerida, id_contenedor)
	}

	pagina_requerida.open('GET', url, true) // asignamos los métodos open y send
	pagina_requerida.send(null)
	//alert ( pagina_requerida.readyState );
}
// todo es correcto y ha llegado el momento de poner la información requerida
// en su sitio en la pagina xhtml
function cargarpaginaXML(pagina_requerida, id_contenedor)
{
	if(pagina_requerida.readyState==1)
	{
	//document.getElementById("cargando").style.visibility = "visible";
	}else if (pagina_requerida.readyState == 4 && (pagina_requerida.status==200 || window.location.href.indexOf("http")==-1))
	{
	//	document.getElementById("cargando").style.visibility = "hidden";
	var i;
	var txt = pagina_requerida.responseXML;
	var fuentes=txt.getElementsByTagName("fuente");
	for(i=0;i<fuentes.length;i++)
	{
	}
	/*var i;
	var fuentes=txt.getElementsByTagName("nombre");
	var nombres+=""; 
	for(i=0;i<fuentes.length;i++)
	 {
	 	nombres+=fuentes.value;
	 	
	 }
	 alert(nombres);
	*/
	//Mostrar_Carpetas(txt);
		
	
	}
}
/////////////////////////////////
/*	var vProxy = "https://www.google.com/tbproxy/spell?lang=";
	var vSpell = new GoogieSpell("gspell/", vProxy);  
	vSpell.decorateTextarea("entradaTexto");*/

///////////////////////////////////
function Mostrar_Carpetas(xmldoc)
{
	 
	 var carpetasNodo=xmldoc.getElementsByTagName("carpeta");
	 
	 
	 var i;
	 //alert(carpetasNodo.length);
	 var cuerpoRef = document.getElementById("carpetas");
	var top=5;
	
	
	 for(i=0;i<carpetasNodo.length;i++)
	 {
	 	
	 	var c=carpetasNodo[i].firstChild;
	 	//alert(c);//c=carpeta
	 	var nombreNodo=c.firstChild;//nombre
	 	//alert(nombreNodo.nodeValue)
	 	var urlNodo=c.nextSibling;//dir
	 	//alert(urlNodo.firstChild.nodeValue);
	 	
	 	var nuevoEnlace = document.createElement("div");
		var nodoTexto = document.createTextNode(nombreNodo.nodeValue);
		nuevoEnlace.appendChild(nodoTexto);	
		nuevoEnlace.setAttribute("id",nombreNodo.nodeValue);
		nuevoEnlace.setAttribute("className","carpeta");
		
		var dir="Bandeja_De_Entrada.php?mensajesUnBuzon="+urlNodo.firstChild.nodeValue;
		//nuevoEnlace.setAttribute("name",dir);
		
		nuevoEnlace.onclick = function()
		{
			
			llamarasincrono(dir,'listadoMensajes');
		};

		nuevoEnlace.style.top=top+"px";
		cuerpoRef.appendChild(nuevoEnlace); 
		top=top+30;
		
	

	 	
      
	 }
	 

}
 
 
	/********** 
		FUNCION QUE CAPTA LOS MENSAJES QUE HAN SIDO SELECCIONADOS Y OBTINENE SU ID,
		BIEN PARA SER BORRADOS, MOVIDOS.....
	*******************/
	function Mostrar(formulario)
	{
		var formulari=document.getElementById("formulario");
		var origen=document.getElementById("origen").value;
        	
		var numMen=formulari.length;
		var msg="Mensajes a eliminar:\n";
		var cont=0;
		var eliminados=new Array();
		for(i=2;i<numMen;i++)//numMen-1
		{
			
			if(formulari.elements[i].checked==true)
			{
				//var mensaje=formulari.elements[i].name;
				var mensaje=formulari.elements[i].name;
				
				//alert(i+"-"+mensaje);
				eliminados[cont]=mensaje;
				msg=msg+mensaje+"\n";
				var origen=document.getElementById("origen").value;
        		var dir="Eliminar_Mensajes.php?mensaje="+mensaje+"&origen="+origen;
        		llamarasincrono(dir,"contenidoMensaje");
				cont+=1;			
			//	Eliminar_Nodo(mensaje);
		
			}
		}
		if(cont==0)
		{
			alert("Seleccciona algún mensaje para eliminarlo");
		}
		else if(cont==1)
		{
			Eliminar_Nodo(mensaje,formulari);
		}
		else
		{
			/*var j;
			for(j=0;j<eliminados.length;j++)
			{
				alert(eliminados[j]);
			}*/
			Eliminar_Varios_Nodos(eliminados,formulari);
			
			//alert(msg);
		}
					
	}
	function Eliminar_Varios_Nodos(arrayNodos,formulari)
 	{
 		var t;
 		for(t=0;t<arrayNodos.length;t++ )
 		{
 		 	var idnodo=arrayNodos[t];
 		 	//alert(idnodo);
 			var ancla = document.getElementById(idnodo);
			var padre = ancla.parentNode;
			var hijoRemovido = padre.removeChild(ancla);
		 	
 		}
 		if(padre.hasChildNodes ())//si el padre tiene mas hijos los reordenamos
		{
		 	var listaHijos=padre.childNodes;
			var i,j;
			var ttop=0;
			for(i=1;i<listaHijos.length;i++)
			{
				var hijo=listaHijos[i];
				var idHijo=hijo.getAttribute("id");
				//alert(idHijo);
				//alert("id: "+idHijo+"posIni: "+hijo.style.top);
				
				document.getElementById(idHijo).style.top=ttop+"px";
				
				ttop=ttop+30;
			}
		
			for(j=1;j<listaHijos.length;j++)
			{
				var hijo=listaHijos[j];
				var nuevoId="m"+j;
				hijo.setAttribute("id",nuevoId);
				hijo.setAttribute("name",nuevoId);
				
			/*	var che=hijo.childNodes;
				var c;
				for(c=0;c<che.length;c++)
				{
					alert(che[c]);
				}*/
			}
			/*cambio de nombre a los checks*/
			var c;
			for(c=2;c<formulari.length;c++)
			{
				var nuevoNombre="m"+(c-1);
				//alert("antes"+formulari.elements[c].name);
				formulari.elements[c].name=nuevoNombre;
				//alert("despues"+formulari.elements[c].name);
				
			}
		/* comprobacion del nuevo id*/
		var listaHijos1=padre.childNodes;
		var k;
		for(k=1;k<listaHijos1.length;k++)
		{
			var hijo1=listaHijos1[k];
			var idHijo1=hijo1.getAttribute("id");
			//alert(idHijo1);
				
		}
		/******************************/
	}
	

 	}
	
	function Mover_a(formulario,e)
	{
		
		var formulari=document.getElementById("formulario");
		var origen=document.getElementById("origen").value;
        	
		var numMen=formulari.length;
		var msg="Mensajes a mover:\n";
		var cont=0;
		var e=new MouseEvent(e);
		//alert(numMen);
		var mensajes="";
		var id_mensaje=new Array();
		for(i=2;i<numMen;i++)
		{
			if(formulari.elements[i].checked==true)
			{
				var mensaje=formulari.elements[i].name;
				msg=msg+mensaje+"\n";
				//alert(msg);
				var origen=document.getElementById("origen").value;
        		var en=e.target.id;
        		var en1=en.split("9999");
        		id_mensaje[cont]=mensaje;
        		mensaje1=mensaje.split("m");
        		mensajes=mensajes+mensaje1[1]+",";
        		
        		cont+=1;
     	    	//Mostrar_Mensajes(origen);			
							
			}
		}
		if(cont==0)
		{
			alert("Seleccciona algún mensaje para moverlo");
		}
		else
		{
			alert(msg);
		}
		
		mensajes=mensajes.substring(0,mensajes.length-1) ;
//alert(en1[1]+"-"+mensajes+"-"+origen);
		llamarasincrono("Mover_Mensajes.php?destino="+en1[1]+"&mensajes="+mensajes+"&origen="+origen,"contenidoMensaje");
     	//Mostrar_Mensajes(origen);	
     	Eliminar_Varios_Nodos(id_mensaje,formulari);
     			
				
				
	}
function Eliminar_Derecho(e)
{
	var e=new MouseEvent(e);

	var origen=document.getElementById("origen").value;
	
	var mensaje=derecho_actual;

	var dir="Eliminar_Mensajes.php?mensaje="+mensaje+"&origen="+origen;
	llamarasincrono(dir,"contenidoMensaje");
							
	Eliminar_Nodo(mensaje);
}
function Eliminar_Carpeta()
{
	
	check = confirm	("Se borrará la carpeta seleccionada y todos los mensajes que hay en ella\n¿Está seguro?");

   		if (check) 
   		{
   			var carpeta=derecho_actual;
   		alert(carpeta);
	var dir="Conectar_Servidor.php?eliminarCarpeta="+carpeta;
	llamarasincrono(dir,"carpetas");
							
//	Eliminar_Nodo(carpeta);
		} 
   		
}
function Responder_Derecho(e)
{
	var e=new MouseEvent(e);
var origen=document.getElementById("origen").value;

	
var mensaje=derecho_actual;
	var dir="Mensaje_Nuevo.php?mensaje="+mensaje+"&buzon="+origen;
        llamarasincrono(dir,"contenido");
llamarasincrono("Botones_2.php","cabecera1");
}
function Marcar_No_Leido_Derecho(e)
{
	var e=new MouseEvent(e);
var origen=document.getElementById("origen").value;

	
	var mensaje=derecho_actual;
	var dir="Conectar_Servidor.php?mensajeM="+mensaje+"&buzon="+origen;
    llamarasincrono(dir,"contenidoMensaje");
    if(document.getElementById(derecho_actual).className=="listadoMails")
    {
    document.getElementById(derecho_actual).className="listadoMailsSinLeer"
    }
    else if(document.getElementById(derecho_actual).className=="listadoMailsCon")
    {
    document.getElementById(derecho_actual).className="listadoMailsSinLeerCon"
    }
    
}
function Marcar_Leido_Derecho(e)
{
	var e=new MouseEvent(e);
var origen=document.getElementById("origen").value;

	
	var mensaje=derecho_actual;
	var dir="Conectar_Servidor.php?mensajeMn="+mensaje+"&buzon="+origen;
    llamarasincrono(dir,"contenidoMensaje");
  //  alert( document.getElementById(derecho_actual).className);
    
    if(document.getElementById(derecho_actual).className=="listadoMailsSinLeer")
    {
    //	alert( document.getElementById(derecho_actual).className);
    document.getElementById(derecho_actual).className="listadoMails"
    }
    else if(document.getElementById(derecho_actual).className=="listadoMailsSinLeerCon")
    {
    	//alert( document.getElementById(derecho_actual).className);    
    	document.getElementById(derecho_actual).className="listadoMailsCon";
    }
    
}
function Seleccionar_Todos()
{
	var formulario=document.getElementById("formulario");
	var numMen=formulario.elements.length;
	if(formulario.todos.checked==true)
	{
		for(i=0;i<numMen;i++)
		{
			formulario.elements[i].checked=true
			
		}
	}
	else
	{
		for(i=0;i<numMen;i++)
		{
			formulario.elements[i].checked=false
			
		}
	}
}
/***********************************************************************
************************************************************************/
/********** FUNCION QUE CAPTA LAS LETRAS INTRODUCIDAS EN UN TEXTBOX Y 
LAS MANDA A UN ARCHIVO PARA PROCESAR 
(SIRVE PARA EL LOGIN AUTOCOMPLETAR LOS USUARIOS ALMACENADOS EN LA BD) 
*** OTRO USO PARA LOS CONTACTOS IR SUGIRIENDO COMO EN HOTMAIL
**********************************************************************/

function Obtener_Sugerencia(keyEvent,tipoInput)
{
	this.sitio_actual=tipoInput;
	//alert(this.sitio_actual);
	
	keyEvent = (keyEvent) ? keyEvent: window.event;
    input = (keyEvent.target) ? keyEvent.target : keyEvent.srcElement;

	
	  if (keyEvent.type == "keyup") 
	  {

	  	
	  	if(keyEvent.keyCode!="13" && keyEvent.keyCode!="37" && keyEvent.keyCode!="38" && keyEvent.keyCode!="39" && keyEvent.keyCode!="40")
	  	{
	  		if (input.value) 
          	{
          	var entrada=input.value;
          	var direcc=entrada.split(";");
          	if(direcc.length==0)
          	{
          		
				var dir= document.getElementById("direcciones");
				dir.style.visibility="visible";
			
				llamarasincrono("Funciones_BD.php?elemento="+input.value,"direcciones");
				anterior=0;
          	}
          	else
          	{
          	
          	var buscar =direcc[direcc.length-1];
				var dir= document.getElementById("direcciones");
			
          	if(buscar!="")
			{
				if(tipoInput=="para")
				{
					dir.style.top="25px";
				}
				else if(tipoInput=="cc")
				{
					dir.style.top="50px";
				}
				else if(tipoInput=="cco")
				{
					
				dir.style.top="75px";
				}
				else if(tipoInput=="contactoLista")
				{
				//alert(dir)	;
				dir.style.top="100px";
				dir.style.left="6px";
				
				}
				dir.style.visibility="visible";
			          	
				llamarasincrono("Funciones_BD.php?elemento="+buscar,"direcciones");
				anterior=0;
			}
			else
			{
				dir.style.visibility="hidden";
			
			}

          	
          	}
		//alert(input.value);
			}
			else
			{
			var vacio="<div></div>";
			llamarasincrono("Funciones_BD.php?elemento="+vacio,"direcciones");
			var dir= document.getElementById("direcciones");
			dir.style.visibility="hidden";
			
			 

		}
	  	}
	
	}
}

function Anadir_Direccion(e)
{
	var e=new MouseEvent(e);
	var dir=document.getElementById(e.target.id);
	var sit=this.sitio_actual;
	
	//alert(sit);
	
	
	var para=document.getElementById(sit);
	var datos=para.value;
	
	var da=datos.split(";");
	var nuevo="";
	
	if(da.length==1)
	{
		
	para.value=e.target.id+";";
	}
	else
	{
		
		for(var i=0;i<da.length-1;i++)
		{
			if(da[i]!=e.target.id)
			{
				nuevo=nuevo+da[i]+";";
			}
		}
		nuevo=nuevo+e.target.id+";";
		para.value=nuevo;
	}
	
	
	
	var dir= document.getElementById("direcciones");
	dir.style.visibility="hidden";
}
/***********************************************************************
************************************************************************/
/***
	* Para conseguir un menu desplegable  
	* al pulsar el boton derecho del raton
	* Ejemplo de uso
	****/
/////////////////////////////////////////////
/////////////////////////////////////////////
/////////////////////////////////////////////


/***********************************************************************
************************************************************************/

	/***
	* Para conseguir activar una funcion cuando el usuario 
	* pulse una tecla
	* Ejemplo de uso
	****/
	var incluir=0;
	var anterior=0;
	var dirAincluir="";

shortcut("Ctrl+Shift+N", function() {
      Mensaje_Nuevo();
});
shortcut("Ctrl+Shift+R", function() {
      Mensaje_Nuevo();
});
shortcut("Ctrl+Shift+E", function() {
     Responder(document.formulario);
});
shortcut("Ctrl+Shift+T", function() {
     Mostrar_RSS();
});
shortcut("Ctrl+Shift+I", function() {
     printit('contenidoMensaje');
});
shortcut("Ctrl+Shift+C", function() {
     Contactos();
});
shortcut("Ctrl+Shift+A", function() {
    Anadir_Carpeta();
});

shortcut("Down", function() {
       Desplazar_Abajo();
});
shortcut("Delete", function() {
       Mostrar(formulario);
});
shortcut("Up", function() {
       Desplazar_Arriba();
});
shortcut("Enter", function() {
       if(incluir==1)
       {
       Anadir_Direccion_Intro(dirAincluir);
       }
       
});

function Desplazar_Abajo()
{
	var direcciones=document.getElementById("direcciones");
	var hijos=direcciones.childNodes;
					
	if(direcciones.style.visibility=="visible")
	{
			if(hijos.length>1)
			{
	
				if(anterior==0)
				{
					var i;
					
						hijos[1].style.background="#A3C1E1";
						anterior=1;
						dirAincluir=hijos[1].id;
						incluir=1;
						hijos[1].style.background="#A3C1E1";
						
					
		
				}
				else
				{

					if(anterior==hijos.length-1)
					{
						hijos[anterior].style.background="#ffffff";
					anterior=1;
						dirAincluir=hijos[1].id;
						incluir=1;
						hijos[1].style.background="#A3C1E1";
					}
					else
					{
						hijos[anterior].style.background="#ffffff";
						hijos[anterior+1].style.background="#A3C1E1";
						
						
						dirAincluir=hijos[anterior+1].id;
						incluir=1;
						anterior=anterior+1;
						
						
					
					}
					
				}
		}
	}

}
function Desplazar_Arriba()
{
	var direcciones=document.getElementById("direcciones");
	var hijos=direcciones.childNodes;
					
	if(direcciones.style.visibility=="visible")
	{
			if(hijos.length>1)
			{
	
				if(anterior==1)
				{
					var i;
						hijos[anterior].style.background="#ffffff";
						hijos[hijos.length-1].style.background="#A3C1E1";
						anterior=hijos.length-1;
						dirAincluir=hijos[hijos.length-1].id;
						incluir=1;
						//hijos[1].style.background="#A3C1E1";
						
					
		
				}
				else
				{

					/*if(anterior==1)
					{
						/*hijos[anterior-1].style.background="#ffffff";
						anterior=1;
						dirAincluir=hijos[1].id;
						incluir=1;
						hijos[1].style.background="#A3C1E1";
					}
					else
					{*/
						hijos[anterior].style.background="#ffffff";
						hijos[anterior-1].style.background="#A3C1E1";
						
						
						dirAincluir=hijos[anterior-1].id;
						incluir=1;
						anterior=anterior-1;
						
						
					
					
					
				}
		}
	}

}
function Anadir_Direccion_Intro(dir)
{
	
	var sit=this.sitio_actual;
	
	
	var para=document.getElementById(sit);
	var datos=para.value;
	var da=datos.split(";");
	var nuevo="";
	
	if(da.length==1)
	{
		
	para.value=dir+";";
	}
	else
	{
		
		for(var i=0;i<da.length-1;i++)
		{
			if(da[i]!=dir)
			{
					nuevo=nuevo+da[i]+";";
			}
			
		}
		nuevo=nuevo+dir+";";
		para.value=nuevo;
	}
	
	anterior=0;
	var dira= document.getElementById("direcciones");
	dira.style.visibility="hidden";
}
////////////////////////////////////////////////////////////////////////////////
	/***
	* Para conseguir que el elemento se mueva con el raton hay que almacenar 
	* las posiciones X e Y del raton respecto de la esquina superior izquierda del elemento 
	* arrastrado.
	****/
  
     var offsetX, offsetY;
     var orden="true";
     var ordenAnterior="";
     
     

	/*************************************
	SE PASA EL OBJETO EVENTO A LA FUNCION CUANDO 
	OCURRE UN EVENTO DE RATON
	* x:  La posicion x del raton (pageX-Firefox,clientX-IE)
	* y: La posicion y del raton (pageY-Firefox,clientY-IE)
	* target: El elemento HTML donde esta el raton (target-Firefox,srcElement-IE)
	
	*** funcion que crea el objeto "MouseEvent" el cual el resto de aplicaciones usaran
	- Nota: Usamos la palabra clave "this" para referirnos al objeto actual.
	**********************************/
	
	 function MouseEvent(e) 
      {
      	/*si el evento que le pasamos es nulo es qeu estamos en IE 
      	y tenemos que crearlo con javascript*/
        if(e) 
        {
          this.e = e; //F
        } else {
          this.e = window.event; //IE
        }

        if(e.pageX) {
          this.x = e.pageX; //F
        } else {
          this.x = e.clientX; //IE
        }

        if(e.pageY) {
          this.y = e.pageY; //F
        } else {
          this.y = e.clientY; //IE
        }

        if(e.target) {
          this.target = e.target; //F
          this.pru=e.currentTarget;
   	
           
        } else {
          this.target = e.srcElement;//IF
            
        }
      }

      
   /*************************************
	* CUANDO EL USUARIO PRESIONA EL RATON PARA ARRASTRAR EL ELEMENTO
	LA FUNCION QUE LLAMAMOS ES ESTA "handleDown".(onmousedown="handleDown(event);)
	
	* A esta funcion se le pasa como argumento el evento en firefox pero no el IE 
	por eso hay que crearlo.
	* Cuando el raton esta presionado, el usuario comenzara a arrastrar 
	el elemnto, el siguiente paso es hacer que el navegador escuche los eventos 
	de movimiento del raton.
	* La funcion "addListener" asocia al evento "mouseMove" (movimiento de raton)
	 la funcion "handleMove".
	

	***********************************/
   	function handleDown(e) //PRESIONAR
  	{
  		
        /* creamos el objeto evento para que nos valga tanto para firefox como IE
        y tener todas sus propiedades */
       
        var e = new MouseEvent(e);
        
      	
      	/* Ocurre cuando el usuario mueve el raton para arrastrar el objeto */
        addListener("mousemove", handleMove);
        /* Ocurre cuando el usuario suelta el elemento */
        addListener("mouseup", handleUp);
        /* Distancia que hay desde la possion inicial del elemento a la posicion del raton */
    
        offsetX = e.x - parseInt(e.target.style.left);
        offsetY = e.y - parseInt(e.target.style.top);
        
        //alert("con valor");
       
        // offsetX = e.x - 0;
        document.getElementById("targetDiv").innerHTML = "";
    }
    function handleDown2(e,mensaje) //PRESIONAR
  	{
  		/* creamos el objeto evento para que nos valga tanto para firefox como IE
        y tener todas sus propiedades */
      	
  		var e = new MouseEvent(e);
      	offsetX = e.x ;//- parseInt(e.target.style.left);
        offsetY = e.y ;//- parseInt(e.target.style.top);
       //alert(e.target.id);
 		//var idd=e.target.getAttribute("id");
 	
 		if(e.target.id!="")
 		{
 		
 			
 			document.getElementById(e.target.id).onclick=function()
        {
        	
        	//document.getElementById(e.target.id).className="listadoMailsOn";
        	var origen=document.getElementById("origen").value;
        	var dir="Mostrar_Un_Mensaje.php?mensaje="+mensaje+"&origen="+origen;
        	llamarasincrono(dir,"contenidoMensaje");
        	//alert(mensaje+"-"+document.getElementById(mensaje).className);
        	if(e.target.className=="listadoMailsSinLeerOn")
      		{
      			
      		
      		document.getElementById(e.target.id).className="listadoMails";
      		}
      		else if (e.target.className=="listadoMailsSinLeerOnCon")
      		{
      	
      		document.getElementById(e.target.id).className="listadoMailsCon";
      	}
        	    	
        	
       
        };
        //	Cambiar_Estilo(id_mensaje,"listadoMailsSeleccionado");
  		
      	/* Ocurre cuando el usuario mueve el raton para arrastrar el objeto */
      	
        addListener("mousemove", handleMove2);
        addListener("mouseup", handleUp2);
  
      	
        
        
        //document.getElementById(e.target.id).style.background="#FFBB00";
        document.getElementById("moviendo").innerText = e.target.id;
     	document.getElementById('moviendo').name=e.target.id;
        
       
 			
 		}
 		
        
        
    }

    /*************************************
	* CUANDO EL USUARIO ARRASTRA EL RATON PARA MOVER EL ELEMENTO
	LA FUNCION QUE LLAMAMOS ES ESTA "handleMove".
	* En esta funcion se ha de mover el <div id=mensaje>.
	* La funcion comienza creado un nuevo objeto "MouseEvent"
	* El elemento html se arrastra a la nueva posicion usando estilos dinamicos
	

	***********************************/
     
	function handleMove(e) //ARRASTRAR
    {	
        var e = new MouseEvent(e);//creamos el evento
        
        var x = e.x - offsetX;//calculamos lo recorrido en el eje X
        e.target.style.left = x + "px";//colocamos el objeto en su nueva coordenada X
        var y = e.y - offsetY;
        e.target.style.top = y + "px";
    }
      
function handleMove2(e) //ARRASTRAR
    {
    	/******/
        
           var e = new MouseEvent(e);//creamos el evento
           	var idd=e.target.getAttribute("id");
            //document.getElementById("informacion").innerText = idd;
         
           document.getElementById('moviendo').style.visibility='visible'; 
        document.getElementById('moviendo').style.left=offsetX+"px";
        document.getElementById('moviendo').style.top=offsetY+"px";
    if(e.target.getAttribute("name")=="carpeta"||e.target.className=="carpeta" )
       
     {
     	document.getElementById('moviendo').innerHTML="<img src=img/ok.gif>aqui si se puede";
     	//document.getElementById(e.target.id).style.background="#ffffff";
     }
     else
     {
     	//document.getElementById(e.target.id).style.background="#ffffff";
     document.getElementById('moviendo').innerHTML="<img src=img/no.gif>aqui NO se puede";
     
     }
    	
		  
        
        //alert("con valor");
       
        // offsetX = e.x - 0;
      //  document.getElementById("informacion").innerHTML = "";
  
    	
    	/*****/
    	
       
        var x = e.x - offsetX;//calculamos lo recorrido en el eje X
       // moviendo.style.left = x + "px";//colocamos el objeto en su nueva coordenada X
        var y = e.y - offsetY;
        //moviendo.style.top = y + "px";
        document.getElementById("moviendo").style.left = e.x + "px";
        document.getElementById("moviendo").style.top = e.y + "px";
    }

	
    /*************************************
	* CUANDO EL USUARIO SUELTA  EL RATON PARA COLOCAR EL ELEMENTO EN SU NUEVA POSICION
	LA FUNCION QUE LLAMAMOS ES ESTA "handleUp".
	* Lo primero es crear el evento con MouseEvent
	* ahora debemos de parar las funciones asociadas a los eventos "mousemove" y "mouseup"
	con la funcion que hemos creado "removeListener".
	* Para soltar el mensaje en la carpeta debemos de obtener la posicion de la carpeta 
	y sus dimensiones

	***********************************/
    
  function handleUp2(e) 
    {
    	
    	
    	//creamos el objeto evento
        var e = new MouseEvent(e);
        
      	var idd=e.target.getAttribute("id");
    	var en=sobre(e);
    	
        //para las funciones asociadas a los eventos anteriores
        removeListener("mousemove", handleMove2);
        removeListener("mouseup", handleUp2);

        // obetnemos los datos de la carpeta donde queremos soltar el mensaje
        var carpeta = document.getElementById(idd);//obtenemos el objeto con el id=carpeta
        //los datos del estilo se obtienen como texto y hay que cambiarlos a enteros con "parseInt"
        var x = parseInt(carpeta.style.left);//coordenada x (respecto a la eskina superior izq)
        var y = parseInt(carpeta.style.top);//coordenada y
        var width = parseInt(carpeta.style.width);// ancho
        var height = parseInt(carpeta.style.height);//alto
		
        // para comprobar si el usuario ha soltao el mensaje dentro de la carpeta
        
       var idamover=document.getElementById("moviendo").name;
      	if(document.getElementById(idamover).className=="listadoMailsSinLeer")
      	{
      	document.getElementById(idamover).className="listadoMails";
      	}
      	else if (document.getElementById(idamover).className=="listadoMailsSinLeerCon")
      	{
      		document.getElementById(idamover).className="listadoMailsCon";
      	}
       
     //   document.getElementById("informacion").innerText=idamover;
        origen=document.getElementById("origen").value;
        
		
   
   		/************
   		var iddd=document.getElementById("moviendo");
        var str ="";
     	for ( var i in iddd){
		str+=i + ": " + iddd.getAttribute(i) + "\n";
		}
		alert(str);
		****************/
   			var nombre=e.target.getAttribute("id");
   			//alert(e.pru.getAttribute("id"));
   			   		if(e.target.className=="carpeta")

     	{
     		mensaje=idamover.split("m");
     		
     		llamarasincrono("Mover_Mensajes.php?destino="+en+"&mensajes="+mensaje[1]+"&origen="+origen,"contenidoMensaje");
     		
     		Eliminar_Nodo(idamover);
     		/*var dir1="Mensajes_Una_Carpeta.php?mensajesUnBuzon="+origen;
     		llamarasincrono(dir1,"listadoMensajes");*/
        
        }
     
       /* if((e.x-10) > x && (e.x-10) < x + width && (e.y-100) > y && (e.y-100) < y + height)
        {
        	
        	llamarasincrono("Mover_Mensajes.php?destino="+en+"&mensaje="+idamover+"&origen="+origen,"informacion");
        	
        	//setTimeout('llamarasincrono("Bandeja_De_Entrada.php?mensajesUnBuzon="+origen,"listadoMensajes")',5000);
        }*/
        document.getElementById('moviendo').style.visibility='hidden'; 
       // document.getElementById(en).style.background='#6AA4D4'; 
        
      }

        
    /*************************************
	* ASOCIA A 1 EVENTO DE RATON LA FUNCION QUE SE QUIERA LLAMAR CUANDO OCURRA ESE EVENTO
	* "type"-> Evento que puede ser "mouseMove" (mover el raton) ó "mouseUp" (soltar el raton)
	* "callback"-> Funcion que queremos llamar cuadno ocurra el evento
	
	***********************************/
      
       function addListener(type, callback) 
       {
       		/**** addEventListener- Añade un evento a un elemento
       		* "type"-> Para definir el tipo de evento que se quiere detectar
       		* "callback"-> La funcion a ejecutar cuando el evento sea activado
       		* "false"-> Lo que se quiere usar para la captura del evento
       		* IE no utiliza la interfaz "EventListener",tiene un conjunto similar de métodos:
       		* attachEvent y detachEvent, que toman parámetros similares,
       		* en "attachEvent" el tipo de evento debe incluir "on" al inicio de la cadena
       		*/
        	//comprobamos si el objeto implementa la interfaz "addEventListener"
       		
       		if (document.addEventListener) 
        	{
          		document.addEventListener(type, callback, false);
        	} 
        	else if (document.attachEvent) //sino sabremos qeu es IE
        	{
          		document.attachEvent("on"+type, callback, false);
        	}
        	else
        	{
        		 alert("No se puede utilizar el manejador de eleventos");
        	}
      }
      /***********************************
      * PARA QUITAR UN EVENTO ASOCIADO A UN ELEMENTO
      * (analoga a la funcion anterior).
      
      ***********************************/
        function removeListener(type, callback) 
       {
       		if (document.removeEventListener) 
        	{
          		document.removeEventListener(type, callback, false);
        	} 
        	else if (document.detachEvent) //sino sabremos qeu es IE
        	{
          		document.detachEvent("on"+type, callback, false);
        	}
        	else
        	{
        		 alert("No se puede utilizar el manejador de eleventos");
        	}
      }
  ///////////////////////////////////////////////////////////////////////////////////////////////
	function Corrector()
	{
	var googie1 = new GoogieSpell("googiespell/", "https://www.google.com/tbproxy/spell?lang=");
	googie1.decorateTextarea("textoMensaje");
	}
 	function sobre(e) //PRESIONAR
  	{
  		var e = new MouseEvent(e);
  		//document.getElementById(e.target.id).style.background="#CFDEEF";
  		return e.target.id;
  	}
  	function Ordenar(tipoOrden)
  	{
  		var sihaymensajes=document.getElementById("listadoMensajes").childNodes;
        
        if(sihaymensajes[0].id=="nohay")
        {
        alert("No hay mensajes para ordenar en esta carpeta");
        
        }
        else
        {
        
        var buzon=document.getElementById('origen').value;
  		var botones=document.getElementById("cabeceraMensajes").childNodes;
        var i;
        for(i=0;i<botones.length;i++)
        {
        	
        	if(botones[i].id==tipoOrden)
        	{
        		if(ordenAnterior!=tipoOrden)
        		{
        			var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=false";
        			orden="true";
        			ordenAnterior=tipoOrden;
        			
        				
        		}
        		else
        		{
        			if(orden=="false")
        			{	
        				var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=false";
        				ordenAnterior=tipoOrden;
        				orden="true";
        			
        			}
        			else
        			{
        				var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=true";
        				ordenAnterior=tipoOrden;
        				orden="false";
        			
        			}
        		}
        		/*if(orden=="false")
        		{	if(ordenAnterior==tipoOrden)
        			{	var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=true";
        				orden="false";
        				document.getElementById('informacion').innerHTML=orden+"<br>ordenAnterior-"+ordenAnterior+"<br>tipoOrden"+tipoOrden;
        				ordenAnterior=tipoOrden;
        				
        			}else{
        				var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=false";
        				orden="true";        			
    					document.getElementById('informacion').innerHTML=orden+"<br>ordenAnterior-"+ordenAnterior+"<br>tipoOrden"+tipoOrden;
        				ordenAnterior=tipoOrden;
        			}       			
        		}
        		else
        		{	if(ordenAnterior==tipoOrden)
        			{	var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=false";
        				orden="true";
        				document.getElementById('informacion').innerHTML=orden+"<br>ordenAnterior-"+ordenAnterior+"<br>tipoOrden"+tipoOrden;
        				ordenAnterior=tipoOrden;
    
        			}else{
        				var dir="Ordenar_Mensajes.php?buzon="+buzon+"&tipoOrden="+tipoOrden+"&ad=false";
        				orden="true";
        				document.getElementById('informacion').innerHTML=orden+"<br>ordenAnterior-"+ordenAnterior+"<br>tipoOrden"+tipoOrden;
        				ordenAnterior=tipoOrden;
    
        			}        			
        		}*/
        		botones[i].className="botonNaranjaOn";
        	}
        	else
        	{
        	
				botones[i].className="botonNaranja";
        	}	
        }
		llamarasincrono(dir,"listadoMensajes");
                
  	}
  	}
  	/*function Ordenar(e)
 	{
 		document.getElementById("menuOrdenar").style.top="126px";
 		document.getElementById("menuOrdenar").style.left="250px";
 		document.getElementById("ordenar").className="ordenarOn";
 		document.getElementById("menuOrdenar").style.visibility="visible";
 		addListener("mousedown", ocultarMenu);
 		addListener("mouseover", cambiarFondo);
 		addListener("mouseout", cambiarFondo1)
 	}
 	function ocultarMenu(e)
 	{
 		var e = new MouseEvent(e);
 		if(e.target.id=="menuOrdenar" ||e.target.id=="ordenarFecha"||e.target.id=="ordenarDe"||e.target.id=="ordenarAsunto" ||e.target.id=="ordenarTamano")
 		{
 			
 			alert(e.target.id);
 			document.getElementById("ordenar").innerHTML=e.target.id;
 			document.getElementById("ordenar").className="ordenar";
 		
 			document.getElementById("menuOrdenar").style.visibility="hidden";
 		
 			removeListener("mousedown", ocultarMenu);
 			removeListener("mouseover", cambiarFondo);
 			removeListener("mouseout", cambiarFondo1);
 		}
 		else
 		{
 			document.getElementById("menuOrdenar").style.visibility="hidden";
 			document.getElementById("ordenar").className="ordenar";
 		
 			removeListener("mousedown", ocultarMenu);
 			removeListener("mouseover", cambiarFondo);
 			removeListener("mouseout", cambiarFondo1);
 		}
 	
 	}*/
 	function cambiarFondo(e)
 	{
 		
 		var e= new MouseEvent(e);
 		if(e.target.className=="tipoOrden" ||e.target.className=="carpeta" || e.target.id=="dpara"||e.target.id=="dcc"||e.target.id=="dcco"||e.target.className=="unContacto")
 		{
 			document.getElementById(e.target.id).style.background="#CFDEEF";
 		}
 		
 		else if( e.target.getAttribute("name")=="botonNaranja")
 		{
 		document.getElementById(e.target.id).className="botonNaranjaOn";
 		
 		}
 		else if( e.target.getAttribute("name")=="boton")
 		{
 		document.getElementById(e.target.id).className="botonOn";
 		
 		}
 		else if( e.target.getAttribute("name")=="elementoMenu")
 		{
 				e.target.style.background="#CFDEEF";
 		}
 		else if(e.target.className=="listadoMailsSinLeer")//e.target.className=="listadoMails" ||
 		{
 				document.getElementById(e.target.id).className="listadoMailsSinLeerOn";
 	
 		}
 		else if(e.target.className=="listadoMailsSinLeerCon")//e.target.className=="listadoMails" ||
 		{
 				document.getElementById(e.target.id).className="listadoMailsSinLeerOnCon";
 	
 		}
 		else if(e.target.className=="listadoMails" )//||e.target.getAttribute("name")=="correoaanadir" ||e.target.getAttribute("name")=="correoaanadir1")//e.target.className=="listadoMails" ||
 		{
 		
 				document.getElementById(e.target.id).className="listadoMailsOn";
 	
 		}
 		else if(e.target.className=="listadoMailsCon" )//||e.target.getAttribute("name")=="correoaanadir" ||e.target.getAttribute("name")=="correoaanadir1")//e.target.className=="listadoMails" ||
 		{
 			
 				document.getElementById(e.target.id).className="listadoMailsOnCon";
 	
 		}
 	}
 	function cambiarFondo1(e)
 	{
 		
 		var e= new MouseEvent(e);
 		
 			if(e.target.className=="listadoMailsOn" )//||e.target.getAttribute("name")=="correoaanadir")
 			{
 				document.getElementById(e.target.id).className="listadoMails";	
 			}
 			else if(e.target.className=="listadoMailsOnCon" )//||e.target.getAttribute("name")=="correoaanadir" ||e.target.getAttribute("name")=="correoaanadir1")//e.target.className=="listadoMails" ||
 			{
 			
 				document.getElementById(e.target.id).className="listadoMailsCon";
 	
 			}
 			else if(e.target.className=="listadoMailsSinLeerOn" )
 			{
 				document.getElementById(e.target.id).className="listadoMailsSinLeer";
 			}
 			else if(e.target.className=="listadoMailsSinLeerOnCon")//e.target.className=="listadoMails" ||
 			{
 				document.getElementById(e.target.id).className="listadoMailsSinLeerCon";
 	
 			}
 			else if( e.target.id=="dpara" ||e.target.id=="dcc"||e.target.id=="dcco"||e.target.getAttribute("name")=="correoaanadir1"||e.target.className=="carpeta")
 			{
 				document.getElementById(e.target.id).style.background="";
 			}
 			/*else if(e.target.className=="unContacto" && this.lista_actual=="")
 			{
 				alert(e.target.id);
 				document.getElementById(e.target.id).style.background="";
 			}*/
 			else if(e.target.className=="unContacto" && this.lista_actual=="")
 			{
 				//alert(e.target.id+"-"+this.lista_actual);
 				document.getElementById(e.target.id).style.background="";
 			}
 			else if(e.target.className=="unContacto" && this.lista_actual!=e.target.id)
 			{
 				//alert(e.target.id+"-"+this.lista_actual);
 				document.getElementById(e.target.id).style.background="";//"#CFDEEF";
 			}
 			else if(e.target.className=="unContacto" && this.lista_actual==e.target.id)
 			{
 				//alert(e.target.id+"-"+this.lista_actual);
 				document.getElementById(e.target.id).style.background="#CFDEEF";
 			}
 			else if(e.target.className=="unContacto" && this.contacto_actual=="")
 			{
 				//alert(e.target.id+"-"+this.contacto_actual);
 				document.getElementById(e.target.id).style.background="";
 			}
 			else if(e.target.className=="unContacto" && this.contacto_actual!=e.target.id)
 			{
 				//alert(e.target.id+"-"+this.lista_actual);
 				document.getElementById(e.target.id).style.background="";//"#CFDEEF";
 			}
 			else if(e.target.className=="unContacto" && this.contacto_actual==e.target.id)
 			{
 				//alert(e.target.id+"-"+this.lista_actual);
 				document.getElementById(e.target.id).style.background="#CFDEEF";
 			}
 			else if( e.target.getAttribute("name")=="boton")
 			{
 				
 			document.getElementById(e.target.id).className="boton";
 			
 			}
 			else if( e.target.getAttribute("name")=="botonNaranja")
 			{
 				if(document.getElementById(e.target.id).className=="botonNaranjaOn")
 				{
 					document.getElementById(e.target.id).className="botonNaranja";
 				}
 				else
 				{
 						document.getElementById(e.target.id).className="botonNaranjaOn";
 				
 				}
 		
 			}
 			else if( e.target.getAttribute("name")=="elementoMenu")
 		{

 				e.target.style.background="#ffffff";

 			}
 		}
 	function Mostrar_Menu_Mover()
 	{
 		document.getElementById("movera").style.display="block";
 	}	
 	function cambiarFondo3(e)
 	{
 		
 		var e= new MouseEvent(e);
 		if(e.target.className=="tipoOrden" ||e.target.className=="carpeta" ||e.target.className=="listadoMails" ||e.target.className=="listadoMailsSinLeer"|| e.target.id=="dpara"||e.target.id=="dcc"||e.target.id=="dcco"||e.target.getAttribute("name")=="correoaanadir" ||e.target.getAttribute("name")=="correoaanadir1" ||e.target.getAttribute("name")=="boton")
 		{
 			//alert("1");
 			document.getElementById(e.target.id).style.background="#CFDEEF";
 		}
 		var texto=document.createTextNode("mensajeX");
 		var etiqueta=document.createElement("div");
 		etiqueta.style.top=e.x;
 		etiqueta.style.top=e.y;
 		
 		
 	}
 	function Crear_Elemento()
 	{
 		var elemento=document.createElement('a');
 		elemento.setAttribute('href', '#');
 		//elemento.style.top='800px';
 		
 		elemento.appendChild(document.createTextNode('hola'));
		elemento.onclick = function(){
	//window.close();
	alert("hey!");
	}

 	}
 	function Anadir_Nodo()
 	{
 	
 	var nuevoEnlace = document.createElement("div");
	var nodoTexto = document.createTextNode("Semblanza");
	nuevoEnlace.appendChild(nodoTexto);	
	
	/*
	var cuerpoRef = document.getElementsByTagName("body")[0];
	cuerpoRef.appendChild(nuevoEnlace);*/
	
	/* Inserta en el elemento en el div que le digamos
	var cuerpoRef = document.getElementById("datos1");
	cuerpoRef.appendChild(nuevoEnlace); 
	**************************************************/
	
	/* Inserta el elemento antes del div */
	var anclaExistente = document.getElementById("datos2");
	var padre = anclaExistente.parentNode;
	var nuevoHijo = padre.insertBefore(nuevoEnlace, anclaExistente);
	/**************************************************/

 	}
 	function Eliminar_Nodo(idnodo,formulari)
 	{
 		if(formulari==null)
 		{
 			var formulari=document.getElementById("formulario");
 		//	alert("que no me has pasado el formulario");
 		}
 	var ancla = document.getElementById(idnodo);
	var padre = ancla.parentNode;
	var hijoRemovido = padre.removeChild(ancla);
	if(padre.hasChildNodes ())//si el padre tiene mas hijos los reordenamos
	{
		var listaHijos=padre.childNodes;
		var i,j;
		var ttop=0;
		for(i=1;i<listaHijos.length;i++)
		{
			var hijo=listaHijos[i];
			var idHijo=hijo.getAttribute("id");
			//alert(idHijo);
			//alert("id: "+idHijo+"posIni: "+hijo.style.top);
			
			document.getElementById(idHijo).style.top=ttop+"px";
			
			ttop=ttop+30;
		}
		
		for(j=1;j<listaHijos.length;j++)
		{
			var hijo=listaHijos[j];
			var nuevoId="m"+j;
			hijo.setAttribute("id",nuevoId);
		}
		/*cambio de nombre a los checks*/
		var c;
		for(c=2;c<formulari.length;c++)
		{
			var nuevoNombre="m"+(c-1);
			//alert("antes"+formulari.elements[c].name);
			formulari.elements[c].name=nuevoNombre;
			
			//alert("despues"+formulari.elements[c].name);
				
		}
		/* comprobacion del nuevo id*/
		var listaHijos1=padre.childNodes;
		var k;
		for(k=1;k<listaHijos1.length;k++)
		{
			var hijo1=listaHijos1[k];
			var idHijo1=hijo1.getAttribute("id");
			//alert(idHijo1);
				
		}
		/******************************/
	}
	
	

 	}
 	
 	/******************************************/
 	function Modificar_Atributos(idnodo)
 	{
 		var ancla = document.getElementById(idnodo);
		 		
 		ancla.setAttribute("title", "Artículos de programación");
		var nuevoTitulo = ancla.getAttribute("title");
		
		
 	}
 	
 	
 	function Ver_Propiedades_Elemento(el) 
 	{
		var str ="";
		for (var i in el)
		{
			str+=i + ":" + el.getAttribute(i) + "\n";
		}
		alert(str);
	}
	var numAdj=0;
	function establecernumAdj(num)
	{
		this.numAdj=num;
	}
	function nuevoFichero() 
	{
		numAdj=numAdj+1;
		var divNuevo=document.createElement('div');
		divNuevo.setAttribute('id', 'div'+numAdj);
		
		var elemento=document.createElement('input');
		var quitar=document.createElement('a');
		var cadena='javascript:Quitar_Adjunto('+numAdj+')';
	 	quitar.setAttribute('href',cadena);
		quitar.setAttribute('id', 'quitar'+numAdj);
		quitar.setAttribute('name', numAdj);//i_cancel.gif
		quitar.setAttribute('className','textoAzulSubrayado');
		/*var imagen=document.createElement('img');
		imagen.setAttribute('src',"img/i_cancel.gif");*/
		var texto=document.createTextNode(" Quitar ");
		quitar.appendChild(texto);
	//quitar.appendChild(imagen);
	
		var input = document.getElementById("adjuntar");
	
 		elemento.setAttribute('type', 'file');
 		elemento.setAttribute('id', 'adjunto'+numAdj);
 		elemento.setAttribute('size', '50');
 		divNuevo.appendChild(elemento);
		divNuevo.appendChild(quitar);
		input.appendChild(divNuevo);
	
		if (navigator.appVersion.indexOf('MSIE') > -1) 
 		{ 
   			elemento.style.display = 'none'; 
   			//elemento.style.position="absolute";
   			elemento.click();
   			var funcion="Realizar_Submit("+numAdj+")";
			setTimeout(funcion,2000);
			
		
			
 		}
		
		/*mover el textbox de debajo conforme añadimos los adjuntos*/
		var texto = document.getElementById("googie");
		
		var altura=texto.style.top;
		var numero=parseInt(altura.charAt(0)+altura.charAt(1)+altura.charAt(2));
		numero=numero+30;
	
		texto.style.top=numero+"px";
	
}

function Realizar_Submit(idd)
{
	var nuevo=document.getElementById("adjunto"+idd).value;
	var texto2=document.createTextNode(nuevo);

	var elemento1=document.getElementById('quitar'+idd);
		//texto2.setAttribute('className','textoAzul');
	elemento1.parentNode.insertBefore(texto2,elemento1);//
	
		
	
	
}
function Quitar_Adjunto(aquitar)
{
	//var elemento1=document.getElementById('quitar'+aquitar);
	//var elemento2=document.getElementById('adjunto'+aquitar);
	var elemento3=document.getElementById('div'+aquitar);
	
	var adjuntar=document.getElementById('adjuntar');
	//adjuntar.removeChild(elemento1);
	//adjuntar.removeChild(elemento2);
	adjuntar.removeChild(elemento3);
	
	var texto = document.getElementById("googie");
	var altura=texto.style.top;
	var numero=parseInt(altura.charAt(0)+altura.charAt(1)+altura.charAt(2));
	numero=numero-30;
	texto.style.top=numero+"px";

	
}
function llamarasincronoPost(url, data, nombrediv)
{ 
  var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("POST", url); 
    XMLHttpRequestObject.setRequestHeader('Content-Type', 
      'application/x-www-form-urlencoded'); 

    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) 
        {
          //callback(XMLHttpRequestObject.responseText); 
          document.getElementById(nombrediv).innerHTML = XMLHttpRequestObject.responseText;

          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
        } 
    }

    XMLHttpRequestObject.send(data); 
  }
}
function Mensaje_Nuevo()
{

llamarasincrono("Botones_2.php","cabecera1");
llamarasincrono("Mensaje_Nuevo.php","contenido");
}


function Responder(formulario)
{
	var formulari=document.getElementById("formulario");
		var numMen=formulari.length;
		var cont=0;
		var origen=document.getElementById("origen").value;
        
		for(i=0;i<numMen;i++)
		{
			if(formulari.elements[i].checked==true)
			{
				var mensaje=formulari.elements[i].name;
				
				var dir="Mensaje_Nuevo.php?mensaje="+mensaje+"&buzon="+origen;
        	cont+=1;			
				
			}
		}
		if(cont==0)
		{
			alert("Seleccciona algún mensaje para responderlo");
		}
		else if(cont>1)
		{
			alert("Esta caracteristica no funciona cuando se seleccionan varios mensajes");
		}
		else
		{
			llamarasincrono(dir,"contenido");
			llamarasincrono("Botones_2.php","cabecera1");
					
		}
		
}

function Reenviar(formulario)
{
	var formulari=document.getElementById("formulario");
		var numMen=formulari.length;
		var cont=0;
		var origen=document.getElementById("origen").value;
        
		for(i=0;i<numMen;i++)
		{
			if(formulari.elements[i].checked==true)
			{
				var mensaje=formulari.elements[i].name;
				
				var dir="Mensaje_Nuevo.php?mensaje="+mensaje+"&buzon="+origen+"&reenviar=si";
       			cont+=1;			
				
			}
		}
		if(cont==0)
		{
			alert("Seleccciona algún mensaje para responderlo");
		}
		else if(cont>1)
		{
			alert("Esta caracteristica no funciona cuando se seleccionan varios mensajes");
		}
		else
		{
		llamarasincrono(dir,"contenido");
	llamarasincrono("Botones_2a.php","cabecera1");
				
		}
		
}


function Responder1(formulario)
{
	var formulari=document.getElementById("formulario");
		var numMen=formulari.length;
		var cont=0;
		for(i=0;i<numMen;i++)
		{
			if(formulari.elements[i].checked==true)
			{
				var mensaje=formulari.elements[i];
				
				var m= mensaje.getAttribute("title");
				
				var part=m.split("<");
				var part1=part[1].split(">");
				//informacion.innerHTML=part1[0]
				
				var dir="Mensaje_Nuevo.php?destinatario="+part1[0];
        	
				cont+=1;			
				
			}
		}
		if(cont==0)
		{
			alert("Seleccciona algún mensaje para eliminarlo");
		}
		else if(cont>1)
		{
			alert("Esta caracteristica no funciona cuando se seleccionan varios mensajes");
		}
		else
		{
		llamarasincrono(dir,"contenido");
				
		}
		
		
	
//llamarasincrono("Botones_2.php","cabecera1");
//llamarasincrono("Mensaje_Nuevo.php?destinatario="+destinatario,"contenido");
/*tinyMCE.init({
	mode : "textareas",
	theme : "advanced"
	

});*/


//llamarasincrono3("Editor.php","contenido");
}
function Mostrar_Mensajes(buzon)
{
	

llamarasincrono("Mensajes.php?mensajesUnBuzon="+buzon,"contenido");
llamarasincrono("Botones_1.php","cabecera1");


}

function Cargar_Editor()
{
tinyMCE.init({
	mode : "textareas",
	theme : "advanced"
	

});
llamarasincrono("Editor.php","adjuntar");

}
function Guardar_Borrador()
{
alert("Guardar borrador");
}
function Cancelar_Mensaje()
{
alert("Cancelar Mensaje");
//llamarasincrono('','');
}
function Reenviar_Mensaje()
{

		var datos=document.getElementsByTagName('input');
	var i;
	var adjuntos="";
	datos1=document.getElementById('oculto');
	datos2=document.getElementById('oculto1');
	
	//alert(datos1.value);
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==0)
		{
		var para=datos[i].value;
		//para=replace("á")
	//	alert(para);
		}
		else if(i==1)
		{
		var cc=datos[i].value;
	//	alert(cc);
		
		}
		else if(i==2)
		{
		var cco=datos[i].value;
		//alert(cco);
		
		}
		else if(i==3)
		{
		var asunto=datos[i].value;
		//alert(asunto);
		
		}
		else
		{
		adjuntos=adjuntos+datos[i].value+";";
	//	alert(adjuntos);
		}
	}
	//var texto=document.getElementById('textoMensaje');
	var inst = tinyMCE.getInstanceById('textoMensaje');
	var txt=inst.getHTML();
	//alert(texto.value);
	//alert(datos1.value);
	var cab=datos1.value;
	var bod=datos2.value;
	
	//txt=texto.value;
	

	llamarasincronoPost('PRUEBARRR.php','para='+para+'&cc='+cc+'&cco='+cco+'&asunto='+asunto+'&adjuntos='+adjuntos+'&texto='+txt+'&cab='+cab+'&bod='+bod,'contenido');
	llamarasincrono("Botones_3.php","cabecera1");

	

}
function Enviar_Mensaje()
{
	var datos=document.getElementsByTagName('input');
	var i;
	var adjuntos="";
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==0)
		{
		var para=datos[i].value;
		//para=replace("á")
		//alert(para);
		}
		else if(i==1)
		{
		var cc=datos[i].value;
		//alert(cc);
		
		}
		else if(i==2)
		{
		var cco=datos[i].value;
		//alert(cco);
		
		}
		else if(i==3)
		{
		var asunto=datos[i].value;
		//alert(asunto);
		
		}
		else
		{
		adjuntos=adjuntos+datos[i].value+";";
		//alert(adjuntos);
		}
	}
	//var texto=document.getElementById('textoMensaje');
	//alert(texto.value);
	//var txt=texto.value;
	
	var inst = tinyMCE.getInstanceById('textoMensaje');
	if(inst!=null)
	{
	var txt=inst.getHTML();
	
	}
	else
	{
	var texto=document.getElementById('textoMensaje');
	var txt=texto.value;
	
	}
	
	

	llamarasincronoPost('PRUEBARRR.php','para='+para+'&cc='+cc+'&cco='+cco+'&asunto='+asunto+'&adjuntos='+adjuntos+'&texto='+txt,'contenido');
	llamarasincrono("Botones_3.php","cabecera1");


}

function Guardar_Borrador()
{
	var datos=document.getElementsByTagName('input');
	var i;
	var adjuntos="";
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==0)
		{
		var para=datos[i].value;
		//para=replace("á")
		//alert(para);
		}
		else if(i==1)
		{
		var cc=datos[i].value;
		//alert(cc);
		
		}
		else if(i==2)
		{
		var cco=datos[i].value;
		//alert(cco);
		
		}
		else if(i==3)
		{
		var asunto=datos[i].value;
		//alert(asunto);
		
		}
		else
		{
		adjuntos=adjuntos+datos[i].value+";";
		//alert(adjuntos);
		}
	}
	//var texto=document.getElementById('textoMensaje');
	//alert(texto.value);
	//var txt=texto.value;
	
	var inst = tinyMCE.getInstanceById('textoMensaje');
	var txt=inst.getHTML();
	// Do you ajax call here
	//alert(inst.getHTML());
	
	llamarasincronoPost('Conectar_Servidor.php','para='+para+'&cc='+cc+'&cco='+cco+'&asunto='+asunto+'&adjuntos='+adjuntos+'&texto='+txt+'&guardar=si','contenido');
	llamarasincrono("Botones_1.php","cabecera1");


}
function Guardar_Cambios()
{
var datos=document.getElementsByTagName('input');
	var i;
	
	for(i=0;i<datos.length;i++)	
	{
		if(i==0)
		{
		var id=datos[i].value;
		
		}
		else if(i==1)
		{
		var nombre=datos[i].value;
		}
		else if(i==2)
		{
		var apellidos=datos[i].value;
		
		}
		else if(i==3)
		{
		var correo=datos[i].value;
				
		}
		else if(i==4)
		{
		var movil=datos[i].value;
		}
		else if(i==5)
		{
		var imagen= datos[i].value;
		
		}
		
		
	}
	
	//var texto=document.getElementById('textoMensaje');
	//alert(texto.value);
	//var txt=texto.value;
	
	llamarasincronoPost('Funciones_BD.php','id='+id+'&nombre='+nombre+'&apellidos='+apellidos+'&correo='+correo+'&movil='+movil+'&imagen='+imagen,'cuadroDetalles');
	

}

function Mostrar_Direcciones(sitio)
{
	this.sitio_actual=sitio;
	var todasDirecciones=document.getElementById("todasdirecciones");
	if(sitio=="para")
	{
	todasDirecciones.style.top="25px";
	}
	else if(sitio=="cc")
	{
		todasDirecciones.style.top="50px";
	}
	else if(sitio=="cco")
	{
	todasDirecciones.style.top="75px";
	}
	todasDirecciones.style.visibility="visible";
	llamarasincrono("Funciones_BD.php?accion=todas","todasdirecciones");
          	
	
//window.open('Ventana_Contactos.php','Ventana_Contactos', "width=120,height=300,scrollbars=NO");
}
function Ocultar_Direcciones()
{
var todasDirecciones=document.getElementById("todasdirecciones");
	todasDirecciones.style.visibility="hidden";
	anterior=0;
}
/*********************************************************
***********************************************************
*************************************************************/

/*********************************************************
******************** editor *************************
*************************************************************/

function ajaxLoad() {
	var inst = tinyMCE.getInstanceById('content');

	// Do you ajax call here
	inst.setHTML('HTML content that got passed from server.');
}

function ajaxSave() {
	var inst = tinyMCE.getInstanceById('content');

	// Do you ajax call here
	alert(inst.getHTML());
}
/*********************************************************
******************** editor *************************
*************************************************************/
var imprimir="";
function Ver_Mensaje_Completo()
{
var mensaje=document.getElementById("contenidoMensaje");
var listado=document.getElementById("listadoMensajes");
var boton1=document.getElementById("verMensajeCompleto");
var boton2=document.getElementById("cerrarMensaje");

var botones=document.getElementById("cabeceraMensajes");
botones.style.visibility="hidden";
boton1.style.visibility="hidden";
boton2.style.visibility="visible";

listado.style.visibility="hidden";
mensaje.style.top="0px";//227//height:215px;
mensaje.style.height="442px";
this.imprimir="si";
}
function Cerrar_Mensaje()
{
	this.imprimir="";

var mensaje=document.getElementById("contenidoMensaje");
var listado=document.getElementById("listadoMensajes");
var boton1=document.getElementById("verMensajeCompleto");
var boton2=document.getElementById("cerrarMensaje");
var botones=document.getElementById("cabeceraMensajes");
botones.style.visibility="visible";
boton1.style.visibility="visible";
boton2.style.visibility="hidden";

listado.style.visibility="visible";
mensaje.style.top="227px";//227//height:215px;
mensaje.style.height="215px";
}

/************************
***************************/
function Contactos()
{
	
	llamarasincrono("Botones_4.php","cabecera1");

	llamarasincrono("pruebaContactos.php","contenido");
//alert("Contactos");
}
var contacto_actual="";
var lista_actual="";
var fuente_actual="";

function Eliminar_Contacto_Derecho(e)
{
	var e= new MouseEvent(e);
	
	//var nuevo=document.getElementById("contactoLista").value;
	var listado=document.getElementById("listasContactos");
	var i;
	var cadena="";
	if(listado.hasChildNodes() )
	{
		var contactosNuevos=listado.childNodes;
	
		for(i=0;i<contactosNuevos.length;i++)
		{
			if(derecho_actual==contactosNuevos[i].getAttribute("id"))
			{
				cadena=cadena;
			}
			else
			{
			var nu="<div style='border-bottom:1px solid #ffffff;' name=contactoNuevo onclick='Seleccionar(event)' id="+contactosNuevos[i].getAttribute("id")+" >"+contactosNuevos[i].getAttribute("id")+"</div>";
			
			cadena=cadena+nu;
			}
		
		}
	}
//	cadena+="<div id="+nuevo+" name=contactoNuevo 'border-bottom:1px solid #ffffff;' onclick='Seleccionar(event)' >"+nuevo+"</div>";
	listado.innerHTML=cadena;
	
	
	
	document.getElementById("contactoLista").value="";

	derecho_actual="";
	

}
function Eliminar_Contacto()
{
		if(contacto_actual!="")
		{
			var check1 = confirm("¿Esta seguro que quiere eliminar este contacto?");
   			if (check1) 
   			{
   				var aeliminar=document.getElementById(contacto_actual);
   				var padre = aeliminar.parentNode;
				var hijoRemovido = padre.removeChild(aeliminar);
				dir="Funciones_BD.php?eliminar="+contacto_actual;
				llamarasincrono(dir,"cuadroDetalles");
				this.contacto_actual="";
   				
   			} 
   			else 
   			{
   				alert("Aqui no se elimina na");
   			
   			}
		}
		else if(lista_actual!="")
		{
			var check1 = confirm("¿Esta seguro que quiere eliminar esta lista de contactos?");
   			if (check1) 
   			{
   				alert(lista_actual);
   				var as=lista_actual.split("l");
				var dir="Funciones_BD.php?eliminarLista="+as[1];
				llamarasincrono(dir,"cuadroDetalles");
				
   				var aeliminar=document.getElementById(lista_actual);
   				var padre = aeliminar.parentNode;
				var hijoRemovido = padre.removeChild(aeliminar);
				
				this.lista_actual="";
   				
   			} 
   			else 
   			{
   				alert("Aqui no se elimina na");
   			
   			}
		}
		else
		{
		alert("Selecciona un contacto o una lista para eliminar");
		}
}
function Eliminar_Fuente()
{
		if(fuente_actual!="")
		{
			var check1 = confirm("¿Esta seguro que quiere eliminar esta fuente?");
   			if (check1) 
   			{
   				var aeliminar=document.getElementById(fuente_actual);
   				var padre = aeliminar.parentNode;
				var hijoRemovido = padre.removeChild(aeliminar);
				//var as=lista_actual.split("f");
				//var dir="Funciones_BD.php?eliminarFuente="+as[1];
				var dir="Funciones_BD.php?eliminarFuente="+fuente_actual;
				
				llamarasincrono(dir,"contenidoMensaje");
				this.fuente_actual="";
   				initialize();
   			} 
   			else 
   			{
   				alert("Aqui no se elimina na");
   			
   			}
		}
		else
		{
		alert("Seleccione una fuente para eliminarla");
		}
}

function Detalles_Contacto(e)
{
	var e=new MouseEvent(e);
	var id=e.target.id;
	Seleccionado(id);

	this.contacto_actual=id;
	var dir="Funciones_BD.php?id="+id;
     llamarasincrono(dir,"cuadroDetalles");
}

function Detalles_Contacto_Lista(e)
{
	var e=new MouseEvent(e);
	var id=e.target.id;
	
	var as=id.split("c");
	var dir="Funciones_BD.php?id="+as[1];
	
        	
	llamarasincrono(dir,"cuadroDetalles");
}
function Editar_Contacto(e)
{
	var e=new MouseEvent(e);
	var id=e.target.id;
	var dir="Funciones_BD.php?editar="+id;
        	
	llamarasincrono(dir,"cuadroDetalles");
}
/**************************
*****************************/
/*********12 mayo 2007 *****************
*****************************/


function Detalles_Lista(e)
{
	var e=new MouseEvent(e);
	var id=e.target.id;
	Seleccionado(id);
	this.lista_actual=id;
	var as=id.split("l");
	var dir="Funciones_BD.php?lista="+as[1];
	
	
	//var dir="Funciones_BD.php?lista="+id;
	
        	
	llamarasincrono(dir,"cuadroDetalles");
}
function Seleccionado(id)
{
	if(this.lista_actual!="")
	{
		
		document.getElementById(this.lista_actual).style.background="";
	}
	else if(this.contacto_actual!="")
	{
			
		document.getElementById(this.contacto_actual).style.background="";
	}
	document.getElementById(id).style.background="#CFDEEF";
	
}
function Detalles_Fuente(e)
{
	var e=new MouseEvent(e);
	var id=e.target.id;
 this.fuente_actual=e.target.id;
	var nom=e.target.getAttribute('name');
	initialize3(id,nom);

}
function CambiarEstilo(id) {
	this.contacto_actual="";
	this.lista_actual="";
	var elementosMenu = document.getElementsByTagName("li");
	for (k = 0; k< elementosMenu.length; k++) {
	elementosMenu[k].className = "inactivo";
	}
	var identity=document.getElementById(id);
	identity.className="activo";
}
function Contacto_Nuevo(usuario)
{
	llamarasincrono('Contactos.php','ContTabul');CambiarEstilo('bt1');
var dir="Funciones_BD.php?anadirContacto="+usuario;
        	alert("Va a añadir un nuevo contacto");        	

	llamarasincrono(dir,"cuadroDetalles");

}
function Fuente_Nueva(usuario)
{
	var dir="Funciones_BD.php?nuevaFuente="+usuario;
    
	llamarasincrono(dir,"contenidoMensaje");

}
function Guardar_Lista()
{
	var datos=document.getElementsByTagName('input');
	var i;
	
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==0)
		{
		var nombreL=datos[i].value;
		}
		//alert(datos[i].value);
		
	}
	/**********************/
	var nombre="-";
	var apellidos="-";
	var movil="-";
	var imagen="-";
	//var correo="-";
		
	//	llamarasincronoPost('Funciones_BD.php','nuevo=a&nombre='+nombre+'&apellidos='+apellidos+'&correo='+correo+'&movil='+movil+'&imagen='+imagen,'cuadroDetalles');
	/****************************/
	var listado=document.getElementById("listasContactos");
	
	var cadena="";
	if(listado.hasChildNodes() )
	{
		var contactosNuevos=listado.childNodes;
	//	alert(contactosNuevos.length);
		
		for(i=0;i<contactosNuevos.length;i++)
		{
			var nu=contactosNuevos[i].getAttribute("id");
			if(nu.indexOf(";",0)!=-1)
			{
				var nu1=nu.split(";");
				cadena=cadena+nu1[0]+";";
				
			}
			else
			{
				cadena=cadena+nu+";";				
			}
			//llamarasincronoPost('Funciones_BD.php','nuevo=a&nombre='+nombre+'&apellidos='+apellidos+'&correo='+nu+'&movil='+movil+'&imagen='+imagen,'cuadroDetalles');
			
			/*if(i==contactosNuevos.length-1)
			{
				alert("entra");
				puede="si";
				
			}*/
		}
		//alert(cadena);
	}

	/******************************/
	llamarasincronoPost('Funciones_BD.php','nuevaLista=a&nombre='+nombreL+'&contactos='+cadena,'cuadroListado');
		document.getElementById("cuadroDetalles").innerHTML="La lista se guardó correctamente";
	//var input = document.getElementById("input")
}
function Guardar_Lista_Editada(id_lista,listadoAnterior)
{
	var datos=document.getElementsByTagName('input');
	var i;
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==0)
		{
		var nombreL=datos[i].value;
		}
	}
	/**********************/
	var nombre="-";
	var apellidos="-";
	var movil="-";
	var imagen="-";
	
	var listado=document.getElementById("listasContactos");
	
	var cadena="";
	if(listado.hasChildNodes() )
	{
		var contactosNuevos=listado.childNodes;
		
		for(i=0;i<contactosNuevos.length;i++)
		{
			var nu=contactosNuevos[i].getAttribute("id");	
			if(nu.indexOf(";",0)!=-1)
			{
				var nu1=nu.split(";");
				cadena=cadena+nu1[0]+";";
				
			}
			else
			{
				cadena=cadena+nu+";";				
			}
	
		}
	
	}

	/******************************/
	llamarasincronoPost('Funciones_BD.php','listaEditada='+id_lista+'&nombre='+nombreL+'&contactos='+cadena+'&listadoAnterior='+listadoAnterior,'cuadroListado');
		document.getElementById("cuadroDetalles").innerHTML="La lista se guardó correctamente";

}
function Editar_Lista()
{
	var dir="Funciones_BD.php?editarLista="+lista_actual;
	llamarasincrono(dir,"cuadroDetalles");
}
function Guardar_Fuente()
{
var datos=document.getElementsByTagName('input');
	var i;
	
	for(i=0;i<datos.length;i++)	
	{
	
		if(i==0)
		{
		var nombre=datos[i].value;
		}
		else if(i==1)
		{
		var url=datos[i].value;
		
		}
		
	}
	llamarasincronoPost('Funciones_BD.php','guardarFuente=a&nombre='+nombre+'&url='+url,'listadoMensajes');
	initialize2();
	//var input = document.getElementById("input")
}

function Anadir_Lista(usuario)
{
	llamarasincrono('Listas.php','ContTabul');
	CambiarEstilo('bt2');
var dir="Funciones_BD.php?anadirLista="+usuario;
alert("Va a añadir una nueva lista");        	
	llamarasincrono(dir,"cuadroDetalles");

        	
	//llamarasincrono(dir,"cuadroDetalles");

}
function Anadir_Contacto_a_Lista()
{
	var nuevo=document.getElementById("contactoLista").value;
	var listado=document.getElementById("listasContactos");
	var i;
	var cadena="";
	if(listado.hasChildNodes() )
	{
		var contactosNuevos=listado.childNodes;
	
		for(i=0;i<contactosNuevos.length;i++)
		{
			var nu="<div style='border-bottom:1px solid #ffffff;' name=contactoNuevo onclick='Seleccionar(event)' id="+contactosNuevos[i].getAttribute("id")+" >"+contactosNuevos[i].getAttribute("id")+"</div>";
			
			cadena=cadena+nu;
		
		}
	}
	cadena+="<div id="+nuevo+" name=contactoNuevo 'border-bottom:1px solid #ffffff;' onclick='Seleccionar(event)' >"+nuevo+"</div>";
	listado.innerHTML=cadena;
	
	
	
	document.getElementById("contactoLista").value="";
	
	
}
function Anadir_Carpeta()
{
	document.getElementById("nuevaCarpeta").style.display="block";
	
	llamarasincrono("nuevaCarpeta.php","nuevaCarpeta");
}
function Guardar_Nombre_Nueva()
{
	var nombreNuevo=document.getElementById("nombreNueva").value;
	var dir="Conectar_Servidor.php?nuevaCarpeta="+nombreNuevo;
	llamarasincrono(dir,"carpetas");
	
	document.getElementById("nuevaCarpeta").style.display="none";
		
}
function Seleccionar(e)
{
var e=new MouseEvent(e);
alert(e.target.id);
}
function Guardar_Contacto()
{
var datos=document.getElementsByTagName('input');
	var i;
	
	for(i=0;i<datos.length;i++)	
	{
		
		if(i==1)
		{
		var nombre=datos[i].value;
		}
		else if(i==2)
		{
		var apellidos=datos[i].value;
		
		}
		else if(i==3)
		{
		var correo=datos[i].value;
				
		}
		else if(i==4)
		{
		var movil=datos[i].value;
		}
		else if(i==5)
		{
		var imagen= datos[i].value;
		
		}
		
	}
	llamarasincronoPost('Funciones_BD.php','nuevo=a&nombre='+nombre+'&apellidos='+apellidos+'&correo='+correo+'&movil='+movil+'&imagen='+imagen,'cuadroDetalles');
}


function Cambiar_Foto()
{
	var elemento=document.createElement('input');
		
	elemento.setAttribute('type', 'file');
 		elemento.setAttribute('id', 'imagen');
 		elemento.setAttribute('size', '50');
 		var imagenAnterior=document.getElementById('imagenActual');
 		imagenAnterior.parentNode.appendChild(elemento);
		
		if (navigator.appVersion.indexOf('MSIE') > -1) 
 		{ 
   			elemento.style.display = 'none'; 
   			//elemento.style.position="absolute";
   			elemento.click();
   			var funcion="Cargar_Nueva_Imagen()";
			setTimeout(funcion,2000);
			
 		}

}
function Cargar_Nueva_Imagen(idd)
{
	var nuevo=document.getElementById("imagen").value;
	var imagen=document.getElementById("imagenActual");
	var contFoto=document.getElementById("contFoto");
	imagen.setAttribute("src",nuevo);
	
	var txt=document.createTextNode(nuevo);
	var salto=document.createElement('br');
	contFoto.appendChild(salto);
	contFoto.appendChild(txt);
	alert(nuevo);
	/*var texto2=document.createTextNode(nuevo);
	var elemento1=document.getElementById('quitar'+idd);
	elemento1.parentNode.insertBefore(texto2,elemento1);*/
	
		
	
	
}
function Cambiar_Tamano_Foto_Mas()
{
	var imagen=document.getElementById("contFoto");
	imagen.style.width="110px";
	imagen.style.background="#FFD96D";
}
function Cambiar_Tamano_Foto_Menos()
{
	var imagen=document.getElementById("contFoto");
	imagen.style.width="100px";
	imagen.style.background="#FFffff";
}

function printit(){  
open('vista_previa.php', 'Sizewindow', 'toolbar=yes') 

	/* var ficha = document.getElementById("vista");
  var ventimp = window.open(' ', 'popimpr');
  ventimp.document.write( ficha.innerHTML );
  ventimp.document.close();
  ventimp.print( );
  ventimp.close();*/

	/*if(this.imprimir=="si")
	{
		
		if (window.print) 
		{
			window.print() ;  
	} 
	else 
	{
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";  
	}


	}*/
}

/**************************
*****************************/
/********************************
/**************** MENU BOTON DERECHO ****************
/********************************
/********************************/
var elemento;
function coord(e) 
{ 
	 if (ns4||ns6)    {  
      coorX = e.pageX+5;  
      coorY = e.pageY+5;  
      elemento=e.target;
   }  
   if (ie)    {  
      coorX = event.x+5;  
      coorY = event.y+5;  
      elemento=event.srcElement;
   }  
   if (document.layers && !document.getElementById){  
     if (e.which == 2 || e.which == 3){  
  
     	Mostrar_Menu() 
      return false;  
     }  
    }  

   return true; 
} 
function Mostrar_Menu() 
{  
	derecho_actual=elemento.id;
if(elemento.getAttribute("name")=="carpeta")
{

   with(document.getElementById("menuCarpeta"))    {  
      style.top = coorY+"px"; 
      style.left =coorX+"px";   
      style.visibility = "visible"; 
   }
}
else if(elemento.getAttribute("name")=="mensaje")
{
derecho_actual=elemento.id;
	with(document.getElementById("menuMensaje"))    {  
	

      style.top = coorY+"px"; 
      style.left =coorX+"px";   
      style.visibility = "visible"; 
   }
}
else if(elemento.getAttribute("name")=="contactoNuevo")
{
derecho_actual=elemento.id;
	with(document.getElementById("menuContacto"))    {  
	

      style.top = coorY+"px"; 
      style.left =coorX+"px";   
      style.visibility = "visible"; 
   }
}
   return false 
}  

function Ocultar_Menu() 
{  derecho_actual="";
   document.getElementById("menuMensaje").style.visibility = "hidden"; 
    document.getElementById("menuCarpeta").style.visibility = "hidden";
   document.getElementById("movera").style.display = "none";//
     document.getElementById("menuContacto").style.visibility = "hidden";

}  

/********************************
/********************************/
function Mostrar_RSS()
{
	llamarasincrono('Botones_5.php','cabecera1');
initialize2();
}
function initialize3(fuente,nom) {
 	
 
    
       var feedControl = new google.feeds.FeedControl();

        feedControl.addFeed(fuente, nom);
       
        feedControl.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
        feedControl.setNumEntries(5);
        feedControl.draw(document.getElementById("contenidoMensaje"), 
                         {drawMode : google.feeds.FeedControl.DRAW_MODE_LINEAR});
    
    }
 function initialize2() {
 	
   var cabe=document.getElementById("cabeceraMensajes"); 
   cabe.innerHTML="<div class=textoAzul style='font-size:13px' ><center><strong>Fuentes RSS<strong></center></div>";
   
  var dir="Funciones_BD.php?mostrarRSS="+usuario;
     llamarasincrono(dir,"listadoMensajes");
    
       var feedControl = new google.feeds.FeedControl();

        feedControl.addFeed("http://www.ELPAIS.com/rss/feed.html?feedId=1", "El País");
        feedControl.addFeed("http://googleblog.blogspot.com/atom.xml", "Google Blog");
        feedControl.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch");
    
        feedControl.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
        feedControl.setNumEntries(2);
        feedControl.draw(document.getElementById("contenidoMensaje"), 
                         {drawMode : google.feeds.FeedControl.DRAW_MODE_LINEAR});
    
    }
   function initialize() {
    var fuentes="";
     var url="Funciones_BD.php?Obtener_RSS="+usuario;
   //**********************************************
 var XMLHttpRequestObject = false; 

  if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new 
     ActiveXObject("Microsoft.XMLHTTP");
  }

  if(XMLHttpRequestObject) {
    XMLHttpRequestObject.open("GET", url); 
 
    XMLHttpRequestObject.onreadystatechange = function() 
    { 
      if (XMLHttpRequestObject.readyState == 4 && 
        XMLHttpRequestObject.status == 200) 
        {
          //callback(XMLHttpRequestObject.responseText); 
        //  document.getElementById(nombrediv).innerHTML = XMLHttpRequestObject.responseText;
         fuentes=XMLHttpRequestObject.responseText;
		
          delete XMLHttpRequestObject;
          XMLHttpRequestObject = null;
        } 
    }

    XMLHttpRequestObject.send(null); 
  }  
   var feedControl = new google.feeds.FeedControl();

  arrayFuentes=fuentes.split(";");
var fuenteynombre="";
var arrayFuente=new Array();

  for(i=0;i<6;i++) //arrayFuentes.length
  {
	fuenteynombre=  arrayFuentes[i];//
	  if(fuenteynombre!="")
	  {	  	
			arrayFuente=fuenteynombre.split("arikitaun");
			feedControl.addFeed(arrayFuente[0], arrayFuente[1]);
      
			
	  }
	 
	  
  }
    
      
    
        feedControl.setLinkTarget(google.feeds.LINK_TARGET_BLANK);
        feedControl.setNumEntries(2);
        feedControl.draw(document.getElementById("informacion"), 
                         {drawMode : google.feeds.FeedControl.DRAW_MODE_TABBED});
    
    }
 
function Vaciar_Papelera()
{
	var dir="Eliminar_Mensajes.php?borrarTodos=si";
        	
				llamarasincrono(dir,"contenidoMensaje");
}
/********************************
/********************************
/********************************/


function shortcut(shortcut,callback,opt) {
	//Provide a set of default options
	var default_options = {
		'type':'keydown',
		'propagate':false,
		'target':document
	}
	if(!opt) opt = default_options;
	else {
		for(var dfo in default_options) {
			if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
		}
	}

	var ele = opt.target
	if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
	var ths = this;

	//The function to be called at keypress
	var func = function(e) {
		e = e || window.event;
		
		//Find Which key is pressed
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;
		var character = String.fromCharCode(code).toLowerCase();

		var keys = shortcut.toLowerCase().split("+");
		//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
		var kp = 0;
		
		//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
		var shift_nums = {
			"`":"~",
			"1":"!",
			"2":"@",
			"3":"#",
			"4":"$",
			"5":"%",
			"6":"^",
			"7":"&",
			"8":"*",
			"9":"(",
			"0":")",
			"-":"_",
			"=":"+",
			";":":",
			"'":"\"",
			",":"<",
			".":">",
			"/":"?",
			"\\":"|"
		}
		//Special Keys - and their codes
		var special_keys = {
			'esc':27,
			'escape':27,
			'tab':9,
			'space':32,
			'return':13,
			'enter':13,
			'backspace':8,

			'scrolllock':145,
			'scroll_lock':145,
			'scroll':145,
			'capslock':20,
			'caps_lock':20,
			'caps':20,
			'numlock':144,
			'num_lock':144,
			'num':144,
			
			'pause':19,
			'break':19,
			
			'insert':45,
			'home':36,
			'delete':46,
			'end':35,
			
			'pageup':33,
			'page_up':33,
			'pu':33,

			'pagedown':34,
			'page_down':34,
			'pd':34,

			'left':37,
			'up':38,
			'right':39,
			'down':40,

			'f1':112,
			'f2':113,
			'f3':114,
			'f4':115,
			'f5':116,
			'f6':117,
			'f7':118,
			'f8':119,
			'f9':120,
			'f10':121,
			'f11':122,
			'f12':123
		}


		for(var i=0; k=keys[i],i<keys.length; i++) {
			//Modifiers
			if(k == 'ctrl' || k == 'control') {
				if(e.ctrlKey) kp++;

			} else if(k ==  'shift') {
				if(e.shiftKey) kp++;

			} else if(k == 'alt') {
					if(e.altKey) kp++;

			} else if(k.length > 1) { //If it is a special key
				if(special_keys[k] == code) kp++;

			} else { //The special keys did not match
				if(character == k) kp++;
				else {
					if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
						character = shift_nums[character]; 
						if(character == k) kp++;
					}
				}
			}
		}

		if(kp == keys.length) {
			callback(e);

			if(!opt['propagate']) { //Stop the event
				//e.cancelBubble is supported by IE - this will kill the bubbling process.
				e.cancelBubble = true;
				e.returnValue = false;

				//e.stopPropagation works only in Firefox.
				if (e.stopPropagation) {
					e.stopPropagation();
					e.preventDefault();
				}
				return false;
			}
		}
	}

	//Attach the function with the event	
	if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
	else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
	else ele['on'+opt['type']] = func;
}
				



  