
/* Funciones basicas VARIOS */

/*
 * Modificaciones:
 *  
 *  22-10-2009: Añadimos soporte de la galeria para poscionamiento estatico independiente del scroll
 *  
 * 
 */


//CARGA INICIAL DE MODULOS DEL PANEL DE CONTROL

function inicialPC()
{
	//Calculamos y asignamos el alto del cuerpo al navegador
	divCuerpoAltoMaximo();
	//Añadimos el evento de redimensionado al navegador
	window.onresize=divCuerpoAltoMaximo;
	//Añadimos las transparencias necesarias a los divs
	divTransparenciasPC();
	//Modulos de carga iniciales del PANEL DE CONTROL
	//traeCodigo('funciones/mensajes.pc.php', '', 'cuerpo_body_superior_01');
	traeCodigo('funciones/menu.pc.php', '', 'cuerpo_menu_superior_01');
	traeCodigo('funciones/barra_herramientas.pc.php', '', 'cuerpo_botonera_superior_01');
	
}

/* Se obtiene desde el skin
function inicialWEB()
{
	//Modulos de carga iniciales de la WEB
	
}
*/

//CIERRE DE SESION AUTOMATICO PARA EL PANEL DE CONTROL 

function cerrarSesionPC()
{
	//Salimos de la sesion actual del Panel de Control
	window.location.href=unescape(window.location.pathname)+'?accion=salir';
}

//ELEMENTOS DE CARGA INICIALES DEL PANEL DE CONTROL 

function cambiarClave()
{
	//Modulos de carga iniciales del PANEL DE CONTROL
	divCuerpoAltoMaximo();
	traeCodigo('funciones/usuarios_clave.pc.php', '', 'cuerpo_body_superior_01');
}

//MUESTRA Y OCULTACIÖN DE LOS DIVS DE CARGA 

function divTransparenciasPC()
{
	//Preparamos las transparencias en los div
	if(document.getElementById('cuerpo_ocultacion_centro_01'))
	{
		bytefx.alpha(document.getElementById('cuerpo_ocultacion_centro_01'), 20);
	}
}

function mostrarCargando(mostrar)
{
	//Colocamos la precarga solo si supera los 2 seg de tiempo
	if(mostrar==true)
	{
		document.getElementById('cargando').innerHTML='<br /><center><img src=imagenes/cargando.gif></img><br><b>Obteniendo Datos</b><br /><a href=javascript:eliminarCargando()>Ocultar</a></center>';
		document.getElementById('cargando').style.visibility='visible';
		document.getElementById('ocultacion').style.visibility='visible';
	}else
	{
		//Preparamos un time que decide si mostrarlo a los 2 segundos devolviendo el identificador del timer
		return setTimeout('mostrarCargando(true)',2000);
	}
}

function eliminarCargando(idTimer)
{
	//Colocamos como oculta la nueva capa de control
	//document.getElementById('cargando').style.visibility='hidden';
	//Limpiamos el intervalo si todavia no ha sido lanzado
	clearTimeout(idTimer);
	//Ocultamos los elementos
	document.getElementById('cargando').style.visibility='hidden';
	document.getElementById('ocultacion').style.visibility='hidden';
}

function mostrarocultarDIV(opt)
{
	//Mostramos ese div si no hay error al obtenerlo
	try
	{ 
		var dv=document.getElementById(opt);
		if(dv.style.visibility=='visible')
		{
			//Lo ocultamos
			ocultarDIV(opt)
		}else
		{
			//Lo mostramos
			mostrarDIV(opt);
		}
	}
	catch(err)
	{
		alert('Error obteniendo el DIV '+opt);
	} 
}

function mostrarDIV(opt)
{
	//Mostramos ese div si no hay error al obtenerlo
	try
	{
		var dv=document.getElementById(opt);
		dv.style.visibility='visible';
	}
	catch(err)
	{
		alert('Error obteniendo el DIV '+opt);
	}
}


function ocultarDIV(opt)
{
	//Ocultamos el div y mostramos error al obtenerlo
	try
	{
		var dv=document.getElementById(opt);
		dv.style.visibility='hidden';
	}
	catch(err)
	{
		alert('Error obteniendo el DIV '+opt);
	}
}


// CAMBIO DE TAMAÑO EN LA FUENTE

function aumentarTamFuente()
{
	//alert(document.body.style.fontSize);
	if(document.body.style.fontSize=='')
	{
		//Si no contiene nada (inicialmente esta vacio) que al inicial (0.7) le sume 0.1
		document.body.style.fontSize='0.9em';
	}else
	{
		//Sustituimos el tipo de tamaño para obtener solo el valor numerio y comprobamos que no sobrepase el tamaño maximo
		var tam=document.body.style.fontSize.replace('em','');
		if(parseFloat(tam)<0.9)
		{
			document.body.style.fontSize=(parseFloat(tam)+0.1)+"em";
		}
	}
}

function reducirTamFuente()
{
	//alert(document.body.style.fontSize);
	if(document.body.style.fontSize=='')
	{
		//Si no contiene nada que al inicial (0.7) le reste 0.1
		document.body.style.fontSize='0.7em';
	}else
	{
		//Sustituimos el tipo de tamaño para obtener solo el valor numerio y comprobamos que no sobrepase el tamaño minimo
		var tam=document.body.style.fontSize.replace('em','');
		if(parseFloat(tam)>0.4)
		{
			document.body.style.fontSize=(parseFloat(tam)-0.1)+"em";
		}
	}
}

function inicialTamFuente()
{
	//Seteamos el tamaño de la fuente al inicial
	document.body.style.fontSize='0.8em';
}

// FUNCIONES DE LAS GALERIAS DE IMAGENES

function mostrarImagen(imagen, posicion, ids, ocultar)
{
	//Mostramos la imagen con un fondo adecuado
	//Parametros opcionales: posicion, ids, ocultar
	//Posicion: posicion de la imagen actual en el array_ids
	//ids: array de ids en base64
	//ocultar: true|false si se hace el efecto de fadein de la capa del fondo
	
	//Eliminamos el efecto de fade
	ocultar=false;
	
	//Calculamos la posicion y el tamaño del fondo de ocultacion
	var x,y;
	if (self.innerHeight) //Todos -IE
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}else if (document.documentElement && document.documentElement.clientHeight)
		//IE6 SM
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;		
	}else if (document.body) //IE6+
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;		
	}

	//Preparamos las cadenas anteriores y posteriores de enlaces si tenemos algo mas que la imagen
	if(posicion>-1 && ids.indexOf("|")>0)
	{
		//Generamos los enlaces anteriores y posteriores
		var array_ids=ids.split('|');
		var enlace=imagen.replace('%IDS%', array_ids[posicion]);
		//Enlace Anterior
		var ant_posicion=0;
		if(posicion<=0) 
		{
			ant_posicion=array_ids.length-1;
		}else
		{
			ant_posicion=posicion-1;
		}
		var enlace_ant="<a href=# onclick=\"javascript:mostrarImagen('"+imagen+"', "+ant_posicion+", '"+ids+"', false);\"><img src=imagenes/fizquierda.png title='Imagen Anterior'/></a>";
		//Enlace siguiente
		var sig_posicion=0;
		if(posicion>=array_ids.length-1) 
		{
			sig_posicion=0 
		}else
		{
			sig_posicion=posicion+1;
		}
		var enlace_sig="<a href=# onclick=\"javascript:mostrarImagen('"+imagen+"', "+sig_posicion+", '"+ids+"', false);\"><img src=imagenes/fderecha.png title='Imagen Siguiente'/></a>";
	}else
	{
		//No tenemos datos para generar los enlaces anteriores y posteriores, generamos solo el enlace de la propia imagen
		//SUPONEMOS que el enlace 'imagen' ya trae montado el ID en la cadena y no por sustitucion de %IDS%
		var enlace=imagen;
		var enlace_ant='';
		var enlace_sig='';
	}
	
	//Comprobamos que queremos volver mostrar el div del fondo
	if(ocultar==false) {}else document.getElementById('imagen').style.visibility='hidden';
	document.getElementById('imagen').innerHTML='<table width='+x+' height='+y+' border=0><tr valign=middle align=center width='+x+' height='+y+'><td style=text-align:right>'+enlace_ant+'</td><td align=center width='+x+' height='+y+'><a href=javascript:cerrarImagen()><img border=0 class=imagen100 src='+enlace+'></a></td><td style=text-align:left>'+enlace_sig+'</td></tr></table>';
	document.getElementById('imagen').style.visibility='visible'
	
	//Comprobamos que queremos volver mostrar el efecto del div de fondo
	if(ocultar==false) {}else bytefx.fade(document.getElementById('imagen'), 25, 100, 40);
}

function cerrarImagen()
{
	bytefx.fade(document.getElementById('imagen'), 100, 0, 40, function() { document.getElementById('imagen').innerHTML=''; document.getElementById('imagen').style.visibility='hidden'; });
	//Ponemos las barras de desplazamiento de la pagina --------- REVISAR problema con el tope superior de las imagenes cuando se cambia de una a otra
	//document.body.style.overflow='';
}

//AUTOMATIZACIÓN DE LA OBTENCIÓN DE CAMPOS DEL FORMULARIO

function obtener_campos(formulario)
{
	var cadena_ajax;
	var campos_error;
	//Si tenemos nodos en el formulario que lo recorra
	if(formulario.hasChildNodes()) 
	{	
		//Recorremos el formulario en todos sus controles
		for (i=0;i<formulario.length;i++)
		{
			//Si no tiene atributo campo es que no necesita salir en la SQL o El envio AJAX
			if(formulario[i].getAttribute('campo'))
			{
				var valor;
				//Segun el tipo de campo de form que sea se tendran que obtener los datos de una manera u otra
				switch(formulario[i].nodeName)
				{
					case 'INPUT':
						//Dentro de los INPUT tenemos los type: text, checkbox, radio
						switch(formulario[i].getAttribute('type'))
						{
							case 'text':
								valor=encodeURIComponent(remplazarURIs(formulario[i].value));
							break;
							case 'hidden':
								valor=encodeURIComponent(remplazarURIs(formulario[i].value));
							break;
							case 'password':
								valor=formulario[i].value;
							break;
							case 'checkbox':
								if(formulario[i].checked)
								{
									valor='1';
								}else{
									valor='0';
								}
							break;
							case 'radio':
								if(formulario[i].checked)
								{
									valor=formulario[i].value;
								}else
								{
									valor='sin seleccion';
								}
							break;
						}
					break;
					case 'TEXTAREA':
						valor=encodeURIComponent(remplazarURIs(formulario[i].value)); //Aunque tambien podemos obtener el valor mediante el texto del primer hijo que es su propio texto
						//alert(formulario[i].value);
					break;
					case 'SELECT':
						if(formulario[i].getAttribute('multiple'))
						{
							//Multiseleccionable SIN USO ACTUAL
						}else
						{	//Una unica seleccion
							valor=formulario[i].value; //Aunque tambien podemos obtener el valor mediante el texto del primer hijo que es su propio texto
						}
					break;
					case 'null':
						//Si no tiene tipo no seria logico que tenga 'campo' pero estas cosas pasan ;)
						valor='VACIO';
					break;
				}
				//Obtenemos el listado de todos los componentes
				if(cadena_ajax==undefined){
					cadena_ajax=formulario[i].getAttribute('campo')+'='+valor;
				}
				else{
					cadena_ajax+='&'+formulario[i].getAttribute('campo')+'='+valor;
				}
				
				//Comprobamos si el filtro del campo ha devuelto error
				if(formulario[i].getAttribute('filtro_ok')=='0'){
					if(campos_error==undefined){
						campos_error='Los siguientes campos contienen errores: \r\n - '+formulario[i].getAttribute('campo');
					}
					else{
						campos_error+='\r\n - '+formulario[i].getAttribute('campo');
					}	
				}
			}
		}
	}
	
	//Si hay errores en los campos los mostramos
	if(campos_error!=undefined){
		alert(campos_error);
		return -1;
	}
	else{
		return cadena_ajax;
	}
}

function remplazarURIs(cadena)
{
	//Remplazamos cualquier posible uri con su equivalente espaciado
	var patron = /(%)(\d)(\d)/g;
	cadena = cadena.replace(patron, "$1 $2$3");
	//alert(cadena);
	return cadena;
}

function comprobar_campos(campo)
{
	var cadena='filtro='+campo.getAttribute('filtro');
	cadena+='&valor='+campo.value;
	cadena+='&id='+campo.id;
	//alert(cadena);
	traeCodigo('../configuracion/comprobar_campos.php', cadena, 'filtro_'+campo.id);
}

//FUNCIONES DE CONTROL DEL EDITOR WYSIG FCK

function MyFCKClass(){
	this.UpdateEditorFormValue = function(){
		for ( i = 0; i < parent.frames.length; ++i )
    	if ( parent.frames[i].FCK )parent.frames[i].FCK.UpdateLinkedField();
   }
}

//FUNCIÓN COMPATIBLE CON TODOS LOS NAVEGADORES PARA OBTENER OBJ EN JS

function returnObjById(id)
{ 
	//Comprobamos la existencia de un objeto para distintos navegadores
    if (document.getElementById) 
        var returnVar = document.getElementById(id); 
    else if (document.all) 
        var returnVar = document.all[id]; 
    else if (document.layers) 
        var returnVar = document.layers[id]; 
    return returnVar; 
}

//CALCULO DE LOS TAMAÑOS DE LAS VENTANAS EN EL PANEL DE CONTROL

function divCuerpoAltoMaximo()
{
	//Obtenemos el area visible de la pantalla y se la asignamos a la ventana interior y al wrapper
	//Calculamos el tamaño de la ventana
	var x,y;
	var divcuerpo='cuerpo_body_superior_01';
	
	if (self.innerHeight) //Todos menos IE
	{
		x = self.innerWidth;
		y = self.innerHeight;
		//Posicionamos el div en la posicion en la que este la web verticalmente (tamaño de pantalla+desplazamiento vertical)
		y_desplazado=window.pageYOffset;
		y_yd = y+y_desplazado;
		var ajuste=5;
	}
	else if (document.documentElement && document.documentElement.clientHeight)	//IE6 Y 7
	{
		if (typeof document.body.style.maxHeight != 'undefined')
		{
			// IE 7, mozilla, safari, opera 9 EN ESTE CASO SOLO PARA IE7
			x = document.body.clientWidth;
			y = document.body.clientHeight;
			y_desplazado = Math.max(document.body.scrollTop,document.documentElement.scrollTop);		
			y_yd = y+y_desplazado;
			var ajuste=5;
			//Ajustamos tambien el ancho para evitar que se lo coma
			//x=x-44;
			//document.getElementById('cuerpo').style.maxWidth=x+'px';
			//document.getElementById('cuerpo').style.width=x+'px';
			//var ajuste=((y*(6000/y))/100);
			//El ajuste no es perfecto para tamaños pequeños
			x=x-(70);
			var x_padding=25;
			/*
			document.getElementById(divcuerpo).style.minWidth=x+'px';
			document.getElementById(divcuerpo).style.width=x+'px';
			document.getElementById(divcuerpo).style.padding=x_padding+'px'; 
			*/
		} else {
			// IE6, older browsers
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
			y_desplazado = Math.max(document.body.scrollTop,document.documentElement.scrollTop);		
			y_yd = y+y_desplazado;
			var ajuste=5;
			//Ajuste corregido de 7200 a 6000 una vez eliminado el espacio superfluo del divhead
			//var ajuste=((y*(6000/y))/100);
			//El ajuste no es perfecto para tamaños pequeños
			x=x-(70);
			var x_padding=25;
			/*
			document.getElementById(divcuerpo).style.minWidth=x+'px';
			document.getElementById(divcuerpo).style.width=x+'px';
			document.getElementById(divcuerpo).style.padding=x_padding+'px';
			*/
		}
	}
	else if (document.body) //IE6+
	{
		//No valido ya que la anterior es valida para IE6 yIE7
	}
	//Tenemos en x el ancho del navegador, en y el alto del navegador, en y_yd el tamaño del alto de la ventana mas lo desplazado por scroll
	// y en y_desplazado el tamaño de desplazamiento hasta el borde superior de la ventana
	//Eliminamos del alto visible el correspondiente a la altura de barraEstado(31), navbar(25aprox) y barraHerramientas(34)
	try{
	y=y-30-34-20-ajuste;
	document.getElementById(divcuerpo).style.maxHeight=y+'px';
	document.getElementById(divcuerpo).style.height=y+'px';
	document.getElementById(divcuerpo).style.minHeight=y+'px';
	}catch(e){}
}

/* GESTION DE IMPRESION */

function imprimir() 
{
	//Imprimimos la web. Falta modificacion para mostrar las propiedades de impresion en IE
	//obtenemos todo lo que tenemos del div cuerpo y lo igualamos al de la impresion de informes para prepararlo para la impresion
	document.getElementById('divDocumentoFondo').innerHTML=document.getElementById('cuerpo').innerHTML;
	mostrarInforme();
	window.print();
	//ocultarInforme();
}

function ocultarInforme()
{
	//Vacio el div y lo oculto despues de imprimirlo o al hacer click
	document.getElementById('divDocumentoFondo').innerHTML='';
	document.getElementById('divDocumentoFondo').style.minHeight='0px';
	document.getElementById('divDocumentoFondo').style.height='0px';
	//Colocamos al div de fondo de los documentos el tamaño minimo de la ventana para que imprima todo en blanco
	document.getElementById('divDocumentoFondo').style.visibility='hidden';
	//Mostramos los combos para evitar problemas de visibilidad en IE6
	document.getElementById('cuerpo').style.visibility='visible';
}

function mostrarInforme()
{
	//Colocamos la altura del div al de la parte visible de la ventana de navegacion como minimo
	var x,y,y_desplazado,y_yd;
	if (self.innerHeight) //Todos-IE
	{
		x = self.innerWidth;
		y = self.innerHeight;
		
		//Posicionamos el div en la posicion en la que este la web verticalmente (tamaño de pantalla+desplazamiento vertical)
		y_desplazado=window.pageYOffset;
		y_yd = y+y_desplazado;
		var ajuste=30;
		document.getElementById('divDocumentoFondo').style.height='auto';
	}else if (document.documentElement && document.documentElement.clientHeight)	//IE6 Y 7
	{
		if (typeof document.body.style.maxHeight != 'undefined')
		{
			// IE 7, mozilla, safari, opera 9 EN ESTE CASO SOLO PARA IE7
			
			x = document.body.clientWidth;
			y = document.body.clientHeight;
			document.getElementById('divDocumentoFondo').style.height='auto';
		}else{
			// IE6, older browsers
			x = document.documentElement.clientWidth;
			y = document.documentElement.clientHeight;
			document.getElementById('divDocumentoFondo').style.minHeight=y+'px';
			//Añadimos que los combos se oculten para evitar que se vean encima
			
			document.getElementById('cuerpo').style.visibility='hidden';
		}
	}
	document.getElementById('divDocumentoFondo').style.minHeight=y+'px';
	document.getElementById('divDocumentoFondo').style.visibility='visible';
}

