/*------------------------------------------------------------------------------
// LIBRERIA DE FUNCIONES JAVASCRIPT 

// Programador: Gustavo Reboso
// Coordinador: Ovidio Gavira, Ascención Cuerva
// Analista: Ovidio Gavira, Ascención Cuerva
// Responsable: Ovidio Gavira, Ascención Cuerva
-------------------------------------------------------------------------------*/

function colocarNombreCentro()
{
	obj = document.getElementById("divLogo");
	
	if ( obj != null )
	{
		obj.style.left = screen.width - 472;
		obj.style.top = "53px";
	}
		
	//document.getElementById("divLogo").style.width = "";
}

/* array contenedor de ventanas popUp abiertas durante la sesion*/
var windows_list = new Array();
var cont = 0;
/*-------------------------------------------------------------------------------
// Función: handlePopupErrors()
// Muestra un mensaje de aviso de javascript indicacndo que se ha intentado
// abrir una ventana PopUp y está ha sido bloqueada por el explorador.
*/
function handlePopupErrors()
	{
		window.alert("Ventana emergente bloqueada.");
		return true;
	}
/*-------------------------------------------------------------------------------
// Función: popUp (name, URL, w, h)
// name: pasar un nombre para la ventana de la siguiente forma: 
//		"popUp" + nombre del formulario + identificador si lo lleva
//		ejemplo: popUpMostrarServicio3 
//		De esta manera si ya hay una ventana abierta con este servicio no se
//		volverá a abrir.
// URL: dirección del código html 
// w: ancho de la ventana PopUp
// h: alto de la ventana PopUp
*/
function popUp(name, URL, w, h) {
	
	var myLeft;
	var myTop;
	
	if((w==0)||(h==0)) {
		myLeft = 0;
		myTop = 0;
		w = screen.width;
		h = screen.height;
	}
	else {
		w=w+60;
		myLeft = (screen.width-w)/2;
		myTop = (screen.height-h)/2;
	}
		
	if(name.indexOf("MostrarServicio")==-1){
		eval("page" + name + " = window.open(URL, '" + name + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=" + w + ",height=" + h + ",left = "+myLeft+",top = "+myTop+"');");
	}
	else {
		eval("page" + name + " = window.open(URL, '" + name + "', 'toolbar=1,scrollbars=1,location=0,statusbar=1,menubar=1,resizable=1,width=" + w + ",height=" + h + ",left = "+myLeft+",top = "+myTop+"');");
	}

	window.onerror = handlePopupErrors;
	eval("page"+name).focus();
	windows_list[cont] = "page"+name;
	cont++;
}

/* PROVISIONAL */
function popUpFijo(name, URL, w, h) {
	
	var myLeft = (screen.width-w)/2;
	var myTop = (screen.height-h)/2;
		
	eval("page" + name + " = window.open(URL, '" + name + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=0,width=" + w + ",height=" + h + ",left = "+myLeft+",top = "+myTop+"');");

	window.onerror = handlePopupErrors;
	eval("page"+name).focus();
	windows_list[cont] = "page"+name;
	cont++;
}
/*-------------------------------------------------------------------------------
// Función popUpModal(name, URL, w, h)
// ...
*/
function popUpModal(name, URL, w, h) {
	var myLeft = (screen.width-w)/2;
	var myTop = (screen.height-h)/2;
	
	eval("page" + name + " = window.showModalDialog(URL, '" + name + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=1,resizable=1,width=" + w + ",height=" + h + ",left = "+myLeft+",top = "+myTop+"');");
	windows_list[cont] = "page"+name;
	cont++;
}

/*-------------------------------------------------------------------------------
// Función maxim ()
// Maximiza una ventana
*/
function maxim () {
	window.top.moveTo(0,0); 
	if (document.all) { 
		top.window.resizeTo(screen.availWidth,screen.availHeight); 
	} 
	else if (document.layers||document.getElementById) { 
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){ 
			top.window.outerHeight = screen.availHeight; 
			top.window.outerWidth = screen.availWidth; 
		} 
	} 
}
/*-------------------------------------------------------------------------------
// Función redim (w,h)
// Redimensiona una ventana y la vuelve a centrar en la pantalla.
// w: nuevo ancho en pixels
// h: nuevo lato en pixels
*/
function redim(w, h) {

	var myLeft = (screen.width-w)/2;
	var myTop = (screen.height-h)/2;
	
	window.top.resizeTo(w,h);
	window.top.moveTo(myLeft, myTop);
}
/*-------------------------------------------------------------------------------
// Función center ()
// Centra la ventana según la resolución de la pantalla.
*/
function center() {
	var myLeft = (screen.width-w)/2;
	var myTop = (screen.height-h)/2;
	
	window.top.moveTo(myLeft, myTop);
}
/*-------------------------------------------------------------------------------
// Función refresh ()
// recarga la página
*/
function refresh () { 
	window.location = window.location.href;
}
/*-------------------------------------------------------------------------------
// Función setSessionOut ()
// Establece el tiempo de sesión de usuario de la página abierta.
// Establece un setTimeOut y pasado este redirecciona la página.
*/
function setSessionTimeOut(time, URL)
{
setTimeout('closeSession(\''+URL+'\');',time);
}
/*-------------------------------------------------------------------------------
// Función closeSession (URL)
// Cierra la sesión del usuario.
// 1. Cierra todas los popUps abiertas
// 2. Redirecciona a URL
*/
function closeSession (URL) {

closePopUps();
window.location.href = URL;

}
/*-------------------------------------------------------------------------------
// Función closePopUps ()
// cierra todas las ventanas popUps abiertas.
*/
function closePopUps () {

// para cada popUp hijo
for (i=0; i < cont; i++){

	// si está abierto
	if(!eval(windows_list[i]).closed){
		// NO CERRAMOS LAS VENTANAS DE MOSTRAR SERVICIOS
		if(windows_list[i].indexOf("MostrarServicio")==-1){
			//si contiene frames
			if(eval(windows_list[i]).frames.length > 0){
				// para cada frame
				for(j=0; j < eval(windows_list[i]).frames.length; j++){
					// si ese frame tiene popUps hijos
					if(eval(windows_list[i]).frames[j].cont > 0) {
						eval(windows_list[i]).frames[j].closePopUps();
					}
				}	
			}
			// si no contiene frames pero tiene popUp hijos a su vez
			else if (eval(windows_list[i]).cont > 0) {
				eval(windows_list[i]).closePopUps();
			}
			// cerramos el popUp
			eval(windows_list[i]).close();
		}
	}
}

}
/*-------------------------------------------------------------------------------
// Función refrescaPortal ()
// refresca la págica principal del portal Alisios.WEB que se debe llamar 'Ppal'
*/
function refrescaPortal () {
var w;
w = window.parent;
if (w.opener) w = w.opener;

while (w.top.name != 'Ppal'){
	w = w.parent;
	w = w.opener;
}
w.location = w.location.href;
}
/*-------------------------------------------------------------------------------
// Función hov (loc, cls)
// modifica la regla de estilo de un elemento loc a cls.
*/
function hov(loc,cls){

   if(loc.className)
      loc.className=cls;
}

/*-------------------------------------------------------------------------------
// Función handleOnClose()
// controla si se ha cerrado el navegador directamente
*/

function handleOnClose() {
   if (event.clientY < 0) {
		//alert(window.location);
		//alert(event.clientY);
		//alert(event.type);
		closePopUps ();
   }
}
/*-------------------------------------------------------------------------------
// Función logOut(path)
// log out de la aplicación:
// - si hay ventanas popUps abiertas se pregunta confirmación  porque se cierran todas
// - si el parámetro path contiene algo se redirecciona la página a path, en otro caso
//	 se cierra la ventana.
*/

function logOut(path, salir) {
	if (cont > 0){
		if (salir)
		{
			closePopUps();
		}
		if(path.length > 0){
			document.location = path;
		} else {
			window.close();
		}
	}else {
		if(path.length > 0){
			document.location = path;
		} else {
			window.close();
		}
	}
	
}
/* FUNCION EN CONSTRUCCION */
/* al cerrar cualquier ventana hay que comprobar si tiene padre
y quitarla del array windows_list del padre y decrementar el contador y rodar los 
otros elelmentos del array ... 
function closeWindow (w) {
alert(w.opener);
	if (w.opener != undefined) {
		for(i=0; i< w.opener.cont; i++) {
			if(w.opener.windows_list[i] == w.name)
				break;	
		}
		w.opener.windows_list[i] = "";
		w.opener.cont--;
	}else if (w.parent != undefined) {
		alert(w.windows_list[0]);
		w.parent.cont--;
	}
	w.close();
}*/

/*-------------------------------------------------------------------------------
// Función genVistaPrevia()
// función que generea la vista previa de un servicio 
*/

function genVistaPrevia() {


	if(document.getElementById('checkVistaPrevia').checked) {
	
		
		if (document.getElementById('labeltextTitulo_CELabelTextBox_CETextBox')){

		document.getElementById('tituloVistaPrevia').value = formateaTexto(document.getElementById('labeltextTitulo_CELabelTextBox_CETextBox').value,29,16);
		}else {
		document.getElementById('tituloVistaPrevia').value = formateaTexto(document.getElementById('TextTitulo').value,29,16);
		}
		
		if (document.getElementById('labeltextDescripcion_CELabelTextBox_CETextBox')) {
		document.getElementById('descripcionVistaPrevia').value = formateaTexto(document.getElementById('labeltextDescripcion_CELabelTextBox_CETextBox').value,50,20);
		}else{
		document.getElementById('descripcionVistaPrevia').value = formateaTexto(document.getElementById('TextDescripcion').value,50,20);
		}
	
		if(document.getElementById('tituloVistaPrevia').value.length > 0)
				document.getElementById('flechaVistaPrevia').style.visibility   = 'visible';
		else
			document.getElementById('flechaVistaPrevia').style.visibility  ='hidden';
			
		if((document.getElementById('tituloVistaPrevia').value.length > 0) || (document.getElementById('descripcionVistaPrevia').value.length > 0)){
		
			
			document.getElementById('divVistaPreviaDegradado').style.visibility = 'visible';
			document.getElementById('divVistaPrevia').style.background='#ffffff';
			document.getElementById('divVistaPrevia').style.border="solid 1px #7f9db9";
			document.getElementById('imageMuestra').style.border="solid 0px #ffffff";
		
			
		}
		else {
			document.getElementById('divVistaPreviaDegradado').style.visibility  = 'hidden';
			document.getElementById('imageMuestra').style.border="solid 1px #7f9db9";
			document.getElementById('divVistaPrevia').style.background='transparent';
			document.getElementById('divVistaPrevia').style.border="solid 0px #ffffff";
	}
	}else{
	
		document.getElementById('flechaVistaPrevia').style.visibility  ='hidden';
		document.getElementById('divVistaPreviaDegradado').style.visibility  = 'hidden';
		document.getElementById('imageMuestra').style.border="solid 1px #7f9db9";
		document.getElementById('divVistaPrevia').style.background='transparent';
		document.getElementById('divVistaPrevia').style.border="solid 0px #ffffff";
		document.getElementById('tituloVistaPrevia').value = '';
		document.getElementById('descripcionVistaPrevia').value = '';
	}
	
	
}
/*-------------------------------------------------------------------------------
// Función formateaTexto (_texto, _longTexto, _longPalabra)
// 
*/
function formateaTexto (_texto, _longTexto, _longPalabra){
	
	var t = _texto;
	if (t.length > 0){
	var i;
	
	//longitud del texto
	
	if(t.length > _longTexto) 
		{
			i = t.lastIndexOf (" ", _longTexto);
			
			if ((i < 0) || (i > _longTexto)){
				i = _longTexto - 3;
				
			}

			t = t.substring (0,i) + " ...";
			
		}
	//palabras muy largas?
	var palabras = new Array();
	palabras = t.split(" ");
	t = '';
	var s;
	
	for(i=0;i<palabras.length;i++)
	{
		if (palabras[i].length > _longPalabra) 
		{
			s = palabras[i].substring(0,_longPalabra - 3) + " ...";
			t = t + ' ' + s;
			break;
		}
		t = t  + palabras[i]+ ' ';
	}
	}
	return t;
}
/*-------------------------------------------------------------------------------
// Función genVistaPrevia()
// función que generea la vista previa de un servicio 

function FChangeFontFamily(id)
{

document.getElementById(id).style.fontFamily='Times New Roman';
document.getElementById(id).style.fontWeight='bold';
document.getElementById(id).style.fontSize='12px';
}
function FChangeFontSize(id, size)
{
alert("entra");

document.getElementById(id).style.fontSize='100%';
var indice;
var objeto = document.getElementById(id);
//var ventana = window.open("","nvent");
for (indice in objeto){
       //ventana.document.write("indice es "+ document.all.idBody[indice]+"<br>");
       //alert(document.all.idBody[indice].name);
       //document.all.idBody[indice].style.fontWeight = 'bold';
     }

}
*/
function FChangeBackground(id, img)
{
if (document.getElementById(id)){
	s = img;
	s = s.replace("%R",screen.width);
	document.getElementById(id).style.background="url("+s+")  center bottom";
	document.getElementById(id).style.backgroundRepeat="no-repeat";

}

}

//-------------------------------------------------------------------------------
// Función shell(command)
// función ejecuta un comando de Windows

function shell(command)
{

RegWsh = new ActiveXObject("WScript.Shell"); 
RegWsh.Run(command); 

}
function prueba(id){
alert("aqui");
alert(document.getElementById(id));
}


/*-------------------------------------------------------------------------------
// MostrarDatosEnDiv()
//
// Muestra/Oculta el div con la informacion
//
// Modificaciones:
// * 28/09/2007 Raúl García
//	- Se cambia la propiedad 'visibility' por 'display'.
*/

function MostrarDatosEnDiv(div, informacion)
{
	if (document.layers) 
	{
		if ( document.layers[div].visibility == 'hidden' )
		{		
			document.layers[div].innerHTML = informacion;
			document.layers[div].visibility='visible';
		}
		else
		{
			document.layers[div].visibility='hidden';
			document.layers[div].height = '1px';
			document.layers[div].innerHTML = "";
		}
	}
	else
	{
		if ( document.getElementById(div).style.display == 'none' )
		{
			document.getElementById(div).style.display = 'block';
			document.getElementById(div).innerHTML = informacion;
		}
		else
			document.getElementById(div).style.display='none';
	}
}

function MostrarDiv(div)
{
	if (document.layers) 
	{
		if ( document.layers[div].visibility == 'hidden' )
		{		
			document.layers[div].visibility='visible';
			document.layers[div].overflow = 'visible';
		}
		else
		{
			document.layers[div].visibility='hidden';
			document.layers[div].height = '1px';	
			document.layers[div].overflow = 'hidden';		
		}
	}
	else
	{
		if ( document.getElementById(div).style.visibility == 'hidden' )
		{
			document.getElementById(div).style.visibility='visible';
			document.getElementById(div).style.overflow = 'visible';
		}
		else
		{
			document.getElementById(div).style.visibility='hidden';
			document.getElementById(div).style.height = '1px';	
			document.getElementById(div).style.overflow = 'hidden';
						
		}
	}
}

/*-------------------------------------------------------------------------------
// MostrarCapaEventos()
//
// Muestra la capa nombreCapa y la situa en las coordenadas del ratón.
// Utiliza getMouseXY() para obtener las coordenadas y guardarlas en MouseX y MouseY.
//
// Se utiliza para mostrar las capas de los eventos del calendario de default.aspx
//
// Modificaciones:
// * 28/09/2007 Raúl García
//	- La capa se muestra encima del raton.
// * 18/10/2007 Raúl García
//  - La capa se muestra debajo del raton para evitar que oculte el día cuando sean muchos eventos.
*/

var MouseX = 0;
var MouseY = 0;

function MostrarCapaEventos(nombreCapa)
{
	getMouseXY();
	
	if (document.layers) 
	{
		document.layers[nombreCapa].visibility='visible';		
		document.layers[nombreCapa].width = '170px';
		//document.layers[nombreCapa].left = MouseX - 200;
		document.layers[nombreCapa].left = 5;
		//document.layers[nombreCapa].top = MouseY;
		document.layers[nombreCapa].top = 210;
		
	}
	else
	{
		document.getElementById(nombreCapa).style.visibility='visible';
		document.getElementById(nombreCapa).style.width = '170px';
		document.getElementById(nombreCapa).style.left = 5; //getAbsPos("panelAgenda").left - MouseX;

		document.getElementById(nombreCapa).style.top = MouseY - getAbsPos("panelAgenda").top + 25; //MouseY - 210;
	}
}

/*-------------------------------------------------------------------------------
// OcultarCapaEventos()
//
// Oculta la capa nombreCapa y la situa en las coordenadas del ratón.
// Utiliza getMouseXY() para obtener las coordenadas y guardarlas en MouseX y MouseY.
//
// Se utiliza para ocultar las capas de los eventos del calendario de default.aspx
*/

function OcultarCapaEventos(nombreCapa)
{
	getMouseXY();
	
	if (document.layers) 
	{
		document.layers[nombreCapa].visibility='hidden';	
		document.layers[nombreCapa].width = '0px';
		document.layers[nombreCapa].left = 0;
		document.layers[nombreCapa].top = 0;
	}
	else
	{
		document.getElementById(nombreCapa).style.visibility='hidden';
		document.getElementById(nombreCapa).style.width = '0px';		
		document.getElementById(nombreCapa).style.left = 0;
		document.getElementById(nombreCapa).style.top = 0;
	}
}


/*-------------------------------------------------------------------------------
// getMouseXY()
//
// Obtiene las coordenadas del puntero del ratón y las almacena en MouseX y MouseY.
// Estas variables son usadas en OcultarCapaEventos() y MostrarCapaEventos()
*/

function getMouseXY() 
{

	var IE = document.all?true:false;

	if (!IE) document.captureEvents(Event.MOUSEMOVE);

	if (IE) 
	{ 
	    tempX = event.clientX + document.body.scrollLeft;
	    tempY = event.clientY + document.body.scrollTop;
	} 
	else 
	{  
		tempX = e.pageX;
		tempY = e.pageY;
  }  
  
  
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;}  
  
  MouseX = tempX;
  MouseY = tempY;
  
  return true;
}


function gotoAnchor (anchorName) {
	url = (window.location.href.indexOf("#") == -1) ? window.location.href : window.location.href.split("#")[0];
	url += "#" + anchorName;
	history.go(0);
	window.location.href = url;
}


function MostrarObservaciones (chkObservacion, divObservacion)
{
	//Ocultamos todos los DIVs de observaciones
	
	//Mostramos/Ocultamos el div de la observacion en base al valor de su checkbox
	obj = document.getElementById(chkObservacion)	
	if ( obj.checked )
	{
		 document.getElementById(divObservacion).style.visibility='visible';
		 document.getElementById(divObservacion).style.overflow = 'visible';
	}
	else
	{
		document.getElementById(divObservacion).style.visibility='hidden';
		document.getElementById(divObservacion).style.height = '1px';	
		document.getElementById(divObservacion).style.overflow = 'hidden';
	}
}
/*-------------------------------------------------------------------------------
// getAbsPos()
// Obtiene la posición absoluta de cualquier elemento HTML.
//
// La función acepta como parámetro el ID de un elemento (una cadena), o el propio
// elemento como objeto. El valor de retorno es también un objeto con dos
// propiedades : top y left, que contienen la posición buscada.
//
// Programador: Raúl García.
//-------------------------
// Historial de versiones:
// * 28/09/2007 Versión 1.0
*/
function getAbsPos(element)
{
  if (typeof element == "string")
    element = document.getElementById(element)
    
  if (!element) return { top:0,left:0 };
  
  var y = 0;
  var x = 0;

  while (element.offsetParent)
  {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}


//...................................................................
function tw_SelectNode (node)
{
alert(node);
o = document.getElementById(node); 

if (o != null){
alert(o.className);

	if (o.className == 'menu_izq_sub_enlace_negrita'){
			o.className = 'menu_izq_sub_enlace';
			//document.getElementById(o.id+"_hidden").value = "off";
	}else{
			o.className = 'menu_izq_sub_enlace';
			//document.getElementById(o.id+"_hidden").value = "on";
	}
}

}
