// Código necesario para cambiar el estilo automáticamente en función de
// un parametro
var sCSS;
var sPathRelativo;

if (sCSS==undefined) sCSS='';
sParametros=window.location.search;
if (sParametros.length>0)
{
	if (sParametros.substr(0,1)=='?') sParametros=sParametros.substr(1);
  aParam=sParametros.split('&');
  for(i=0; i<aParam.length; i++)
  {
  	sParam=aParam[i];
		aPareja=sParam.split('=');
		if (aPareja.length==2)
		{
			if (aPareja[0].toLowerCase()=='css')
			{
				sCSS=aPareja[1];
			}
		}
	}
}
if(sPathRelativo==undefined)
{
	sPathRelativo='../../css/';
}
if(sCSS.length>0)
{
  if (NavegadorIE()) document.createStyleSheet( sPathRelativo+ sCSS + '.css');
  else
  {
		if (document.styleSheets.length>0)
		{
			var sPath,iPos;
			sPath=window.location.pathname;
			iPos=sPath.lastIndexOf('/');
			if (iPos>0)
			{ 
				sPath=sPath.substring(0,iPos+1);
				sPath=sPath + sPathRelativo + sCSS + '.css';
				oCSS=document.styleSheets.item(document.styleSheets.length-1);
				while (oCSS.cssRules.length>0) oCSS.deleteRule(0);
				oCSS.insertRule('@import url(' + sPath + ');',0);
			}
		}
  }
}



// Función utilizada para gestionar los links en el caso de trabajar con múltiples CSS
function GestionarEnlace(sEnlace, w, h, iURL, iVentanaNueva, sTarget,iHTTPS){
	//Le pasamos el parametro (si tiene)
	if ((sCSS.length>0)&&(sEnlace.indexOf("javascript:")==-1))
	{
		if (sEnlace.indexOf("?")==-1) sEnlace=sEnlace + '?css=' + sCSS;
		else sEnlace=sEnlace + '&css=' + sCSS;
	}
	
  sEnlace=CalcularURLHTTPS(sEnlace,iHTTPS);

	//Comprobamos el destino del link
	if (iVentanaNueva==0)	{
		if (sTarget.length==0) 
	    window.open(sEnlace,'_self');
		else
      window.open(sEnlace,sTarget);
	}
	else {
		abrirVentana(sEnlace,w,h,iURL);
	}
}


												

function GestionarEnlaceParams(sEnlace, iWidth, iHeight, iURL, iVentanaNueva, sTarget, iHTTPS, sParams)
{
	var oCampo,aRelServicio,aParejaRel,sValor,oFormLink,oCampoOculto,i,oVentana,sNombreVentana,iTop,iLeft,sFeatures,aParams;

  
	//Buscamos el formulario que utilizaremos para simular un link y le quitamos todos los campos que tenga.
	oFormLink=document.getElementById('frmLink');
	if (oFormLink)
	{
		while (oFormLink.childNodes.length>0)
			oFormLink.removeChild(oFormLink.childNodes.item(0));
	}
	else
	{
			document.write('<form id="frmLink" name="frmLink" method="POST"></form>');
			oFormLink=document.getElementById('frmLink');
	}

	//Por cada campo anadimos un campo oculto al formulario con su valor
	aRelServicio=sParams.split('&');

	for(i=0;i<aRelServicio.length;i++)
	{
		//Buscamos el valor del campo
		aParejaRel=aRelServicio[i].split('=');
		
		//** AGA 20/09/2006: Paso de parámetros entre formularios
		// La codificación de la relación de campos entre páginas puede ser de 2 maneras:
		//  - Campos resultado consulta (sistema tradicional):
		//				En la parte derecha del igual está el nombre del campo resultado de la consulta
		//  - Parámetro (sistema nuevo):
		//				En la parte derecha del igual está el tipo de parámetro (CMP=campo o VAL=valor)
		//        y el valor (nombre del campo en el form o valor, respectivamente) separados
		// 				por la secuencia de control "|$|"

		aParams=aParejaRel[1].split('|$|');
		
		if (aParams.length == 2)
		{
			// Relación por parámetro
			switch(aParams[0])
			{
				case 'CMP':
					oCampo=document.getElementById(aParams[1]);
					if (oCampo!=null) sValor=oCampo.value;
					else sValor='';
					break;
				
				case 'VAL':
					sValor=URLDecode(aParams[1]);
					break;
				
				default:
					sValor='';
					break;
			}
			//Creamos un campo oculto y lo anadimos al formulario
			oCampoOculto=document.createElement('INPUT');
			oCampoOculto.type='hidden';
			oCampoOculto.name=aParejaRel[0];
			oCampoOculto.value=sValor;
			oFormLink.appendChild(oCampoOculto);				
		}
	}
	
	
	//Comprobamos si el resultado hay que mostrarlo en otra ventana o no
	if (iVentanaNueva==1)
	{
	  // Calculamos la posicion de la ventana para que salga en el centro
		iLeft=Math.round((window.screen.availWidth-iWidth)/2);
	  if (iLeft<0) iLeft=0;
		iTop=Math.round((window.screen.availHeight-iHeight)/2);
	  if (iTop<0) iTop=0;
		if (iVentanaNueva==0) sFeatures='scrollbars=yes,resizable=yes';
		else sFeatures='menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,location=yes';
		sFeatures=sFeatures.concat(',width='+iWidth+',height='+iHeight+',left='+iLeft+',top='+iTop);

		// Abrimos la nueva ventana
		sNombreVentana='_EDW_popup_';
		oVentana=window.open('about:blank',sNombreVentana,sFeatures);
		oFormLink.target=sNombreVentana;
		oVentana.focus();
	}
	else 
	{
		if (sTarget.length==0) 
    	oFormLink.target='_self';
		else
			oFormLink.target='sTarget';
	}

	//Ejecutamos el link
	sEnlace=CalcularURLHTTPS(sEnlace,iHTTPS);
	if (sEnlace.lastIndexOf('?')>0)
		oFormLink.action=sEnlace.concat('&procedencia=Parametros');
	else
		oFormLink.action=sEnlace.concat('?procedencia=Parametros');
	oFormLink.submit();

	if (oFormLink.target != '_self' && NavegadorIE()) { history.back();}
}


function CalcularURLHTTPS(sEnlace,iHTTPS)
{
  var sNuevoEnlace, sPathBase;
  var bCambiarProtocolo=false;
  var lPos;
   sNuevoEnlace=sEnlace;
   if (iHTTPS!="2")
   {
     if ((sEnlace.indexOf("http://")==-1)&& (sEnlace.indexOf("https://")==-1))
     {
        if (self.location.protocol=="http:" && iHTTPS==1) bCambiarProtocolo=true;
        if (self.location.protocol=="https:" && iHTTPS==0) bCambiarProtocolo=true;
        if (bCambiarProtocolo)
        {
          if (iHTTPS==0) sNuevoEnlace="http://";
          if (iHTTPS==1) sNuevoEnlace="https://";
          sNuevoEnlace=sNuevoEnlace + self.location.host;
          if(self.location.port!="")  sNuevoEnlace=sNuevoEnlace + ":" + self.location.port;
          sPathBase=self.location.pathname;
          lPos=sPathBase.lastIndexOf("/");
          if (lPos!=-1)
          {
            sPathBase=sPathBase.substring(0,lPos-1);
           }
          sNuevoEnlace=sNuevoEnlace+sPathBase + "/" +sEnlace;
        }    
        
      }
   }
      return sNuevoEnlace;
}



//Abre una nueva ventana con la URL indicada
function abrirVentana(enlace, w, h, iURL)
{
  var ileft,itop;

  /* Calculamos la posición de la ventana para que salga en el centro */
	ileft=Math.round((window.screen.availWidth-w)/2);
  if (ileft<0) ileft=0;
	itop=Math.round((window.screen.availHeight-h)/2);
  if (itop<0) itop=0;

	/* Si se trata de una URL, mostramos todas las barras de la navegación */  
  if (iURL == 0)
  {
  	win2 = window.open(enlace,'_blank','scrollbars=yes,resizable=yes,width='+w+',height='+h+',left='+ileft+',top='+itop); 
  }
  else
  {
  	win2 = window.open(enlace,'_blank','menubar=yes,toolbar=yes,scrollbars=yes,resizable=yes,location=yes,width='+w+',height='+h+',left='+ileft+',top='+itop); 
  }    

	/* Ponemos el foco en la nueva ventana */    
 	try {   win2.focus(); }
	catch(ex) {  }
}
function abrirDocumento(enlace, w, h)
{
  var ileft,itop;

  /* Calculamos la posición de la ventana para que salga en el centro */
	ileft=Math.round((window.screen.availWidth-w)/2);
  if (ileft<0) ileft=0;
	itop=Math.round((window.screen.availHeight-h)/2);
  if (itop<0) itop=0;

	/* mostramos solo las barras de menu */  
  	win2 = window.open(enlace,'_blank','menubar=yes,scrollbars=yes,resizable=yes,width='+w+',height='+h+',left='+ileft+',top='+itop); 
	/* Ponemos el foco en la nueva ventana */    
    win2.focus();
}
 //Abre una nueva ventana OCULTA con la URL indicada
function abrirVentanaOculta(enlace)
{
  	win2 = window.open(enlace,'oculta','scrollbars=no,resizable=no,toolbar=no,titlebar=no,status=no,location=no,width=1,height=1,left=0,top=0');  
    self.focus();
}
//funciones relacionadas con los menús Flash
//Captura el nombre del directorio y lo envia al menu flash
function obtenerUrl(){
			//cadenaUrl = location.pathname;
			if(parent.frames[0]){
				cadenaUrl = parent.frames[0].location.href;
			}else{
			 cadenaUrl = location.pathname;
			}
			partesUrl = cadenaUrl.split("/"); // la contrabarra se escribe doble: \\
			seccion= partesUrl[partesUrl.length-2];
			return seccion
	}

//envia el valor de la variable al archivo flash
function pasaVariable() 
{
	if(document.flsMenu)
	{
			document.flsMenu.SetVariable("_root.carpeta",obtenerUrl());
	}
	return 0;
}
//inserta la fecha
function fecha(){
var ahora=new Date();
var anyo=(ahora.getYear()<1000)?ahora.getYear()+1900:ahora.getYear();
var mes=ahora.getMonth()+1;
var dia=ahora.getDate();
mes=(mes<10)?"0"+mes:mes;
dia=(dia<10)?"0"+dia:dia;
  document.write(dia+"."+mes+"."+anyo);
}

//--------------------------------------------------
//	Función para identificar el navegador que está
//	utilizando el cliente
//--------------------------------------------------
function NavegadorIE() {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return true;
	} else {
		return false;
	}
}


//--------------------------------------------------
//	Funcions per ocultar les seccions que no es
//	volen imprimir
//--------------------------------------------------
function antesImpresion()
{
  var oItm; 
  for(i = 0; i < document.all.length; i++)
  {
    oItm = document.all(i);
	  if ("clsNoImprimir" == oItm.className) oItm.className = "clsOcultarAlImprimir";
  }
}

function despuesImpresion()
{
  var oItm; 
  for(i = 0; i < document.all.length; i++)
  {
    oItm = document.all(i);
    if ("clsOcultarAlImprimir" == oItm.className) oItm.className = "clsNoImprimir";
  }
}

window.onbeforeprint=antesImpresion;
window.onafterprint=despuesImpresion;


/************************************************/
/************** Gestion de cookies **************/
/************************************************/
function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	
	while (i < clen) 
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function setCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

/************************************************/
/************** Gestion de estilos **************/
/************************************************/


function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  setCookie("style", title, 365);
}

function cargaEstiloPersonalizado()
{
	var cookie = readCookie("style");
	var title = cookie ? cookie : getPreferredStyleSheet();
	setActiveStyleSheet(title);
}




//--------------------------------------------------
//	Función para inversa al Server.UrlEncode de ASP
//--------------------------------------------------
function URLDecode(texto)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = texto;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}


