// alias para document.getElementById
function $(id){
    return document.getElementById(id);
}

/****** Calcular cuanto se ha desplazado el scroll de la pantalla ******/

function calcularScroll(){
    var x,y;
    if (self.pageYOffset) // all except Explorer
    {
    	x = self.pageXOffset;
    	y = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    	// Explorer 6 Strict
    {
    	x = document.documentElement.scrollLeft;
    	y = document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
    	x = document.body.scrollLeft;
    	y = document.body.scrollTop;
    }
    
    resultado=new Array(x,y);
    
    return resultado;

}

/****** Comprueba si el navegador es Internet Explorer ******/
function esIE(){
    var agt=navigator.userAgent.toLowerCase();
    return ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
}

/****** Registra un evento sobre un objeto (multi-plataforma) ******/

function anyadirEvento(objeto,evento,funcion){
	try{
		objeto.addEventListener(evento,funcion,false);
		return true;
	}catch(e){
		try{
			objeto.attachEvent("on"+evento,funcion);
			return true;
		}catch(e){
			return false;
		}
	}
}

/***** Altera la opacidad de un elemento ******/

function cambiarOpacidad(objeto,op){    
	objeto.style.filter="alpha(opacity="+op+")";
	objeto.style.MozOpacity=op/100;
	objeto.style.opacity=op/100;
}

/********ventanaEmergente**********
texto_id = id del div que contiene el HTML a mostrar en la ventana
x,y posicion de la pantalla donde se muestra la ventana
minancho, minalto: dimensiones minimas de la ventana (se alarga para  que quepa el texto)
****************************************/
    function ventanaEmergente(texto_id,x,y,minancho,minalto,titulo){
        if (document.getElementById('emergente')){
            quitarDiv(document.getElementById('emergente'));
        }
        this.IE=esIE();
        this.minancho=minancho;
        this.minalto=minalto;
        this.sumaX=minancho/minalto*12;
        this.sumaY=12;
        this.ancho=0;
        this.alto=0;
        this.interv=null;
        this.desplegado=false;
        this.detalle=document.createElement("div");
        this.detalle.setAttribute("class","detalle");
        this.detalle.setAttribute("className","detalle");
        this.detalle.setAttribute("id","emergente");
        this.detalle.style.width="0px";
        this.detalle.style.minHeight="0px";
        if (IE){
            this.detalle.style.height="0px";
        }

        this.despl=calcularScroll();
        
        this.detalle.style.top=y+this.despl[1]+"px";
        this.detalle.style.left=x+this.despl[0]+"px";
        
        //creamos la barra del título;
        this.barratitulo=document.createElement("div");
        this.barratitulo.setAttribute("class","barradesc");
        this.barratitulo.setAttribute("className","barradesc");
        
        //creamos el aspa y la añadimos
        this.aspa=document.createElement("img");
        this.aspa.setAttribute("src","/images/iconos/aspa.gif");
        this.aspa.setAttribute("class","aspa");
        this.aspa.setAttribute("className","aspa");
        this.aspa.setAttribute("onclick","quitarDiv(this.parentNode.parentNode)");
        if (IE){
            this.aspa.onclick=quitarDiv;
        }
        
        this.barratitulo.appendChild(this.aspa);
        
        //creamos el titulo y lo añadimos al agrandar
        this.etiquetatitulo=document.createElement("span");
        this.etiquetatitulo.style.maxWidth=(minancho-50)+"px";
        this.titulov=document.createTextNode(document.getElementById(texto_id).title);

        
        this.barratitulo.appendChild(this.etiquetatitulo);
        
        

        
        //creamos el contenedor del texto
        this.contenido=document.createElement("div");
        this.contenido.setAttribute("class","contenidotexto desarrollo");
        this.contenido.setAttribute("className","contenidotexto desarrollo");
        this.contenido.style.width=(this.minancho-50)+'px';
        this.contenido.innerHTML=document.getElementById(texto_id).innerHTML;
        
        this.detalle.appendChild(this.barratitulo);
                
        this.id_texto=texto_id;
        document.getElementsByTagName('body')[0].appendChild(this.detalle);  
        this.interv=window.setInterval("agrandarDiv()",1);

        this.agrandarDiv=function(){
            if (this.ancho< this.minancho){
                this.detalle.style.width=this.ancho+"px";
                this.detalle.style.minHeight=this.alto+"px";
                if (IE){
                    this.detalle.style.height=this.alto+"px";
                }
                this.ancho+=sumaX;
                this.alto+=sumaY;
                this.detalle.style.top=y+this.despl[1]-this.alto+"px";
                this.detalle.style.left=x+this.despl[0]-this.ancho+"px";
            }else{
                clearInterval(this.interv);
                desplegado=true;
              //  detalle.innerHTML=document.getElementById(id_texto).innerHTML;
                      this.etiquetatitulo.appendChild(this.titulov);
                this.detalle.appendChild(this.contenido);
            }
        }
        
}        
    
function quitarDiv(detalle){
    if (IE && !detalle) detalle=this.parentNode.parentNode;
    if (detalle.parentNode){
          detalle.style.display='none';
          detalle.innerHTML='';
          detalle.parentNode.removeChild(detalle);
          desplegado=false;
          ancho=0;
          alto=0;
    }
}

//crea un objeto del tipo XMLHttpRequest según el navegador
function XML(){ //no quitar los comentarios condicionales
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}


//rellena un select con el contenido de una array con la estructura [texto: "eltexto", valor: "elvalor,....]
function rellenarSelect(obj,contenido){
 /*   tamanyo=obj.length; 
    for(i=0;i<tamanyo;i++){
        obj.options[0]=null;
    }
    */
    obj.innerHTML="";

    tamanyo=contenido.length;
    for(i=0;i<tamanyo;i++){               
        obj.options[i]=new Option(contenido[i].texto,contenido[i].valor);
    }
}


//selecciona la opción de un select que tenga como valor el parametro
function seleccionarSelect(obj,valor){
    tamanyo=obj.options.length;
    for(var i=0;i<tamanyo;i++){
          if(obj.options[i].value==valor){
            obj.options[i].selected=true;  
          } 
    }
}

function popUp(direccion){
    ventana=window.open(direccion,'','toolbar=0');
    ventana.focus();  
}

function esAncestro(padre,hijo){
    try{
        if(hijo==padre)
            return true;
        if(hijo.tagName=="BODY")
            return false;
        return esAncestro(padre,hijo.parentNode);
    }catch(ex){
        return false;  
    }
}

function menuHover(idMenu){
    tags=document.getElementsByTagName("a");
    imagenes_off=[];
    imagenes_on=[];
    for(var k=0;k<tags.length;k++){
        if(esAncestro($(idMenu),tags[k])){
            imagenes_off[tags[k].href]=new Image();
            imagenes_off[tags[k].href].src=tags[k].firstChild.src; 
            imagenes_on[tags[k].href]=new Image();
            imagenes_on[tags[k].href].src=tags[k].firstChild.src.replace(/(.*)(.gif)|(.jpg)|(.png)/,"$1on$2");
            tags[k].onmouseover=function(){
                this.firstChild.src= imagenes_on[this.href].src;
            }
            tags[k].onmouseout=function(){ 
                this.firstChild.src= imagenes_off[this.href].src;
            }
        }
    }
}

function getStyle(x,styleProp)
{
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function coloresInput(color_focus,color_blur){
      var etiquetas=['input','textarea'];
      for (var k=0;k<etiquetas.length;k++){                 
         tags=document.getElementsByTagName(etiquetas[k]);     
           for(var q=0;q<tags.length;q++){
              anyadirEvento(tags[q],"focus",function(){this.style.backgroundColor='#'+color_focus});
              anyadirEvento(tags[q],"blur",function(){this.style.backgroundColor='#'+color_blur});
           }
      }
}

function transicionFondo(elemento,inicio,fin,tiempo,atributo){
    if(!atributo) atributo="backgroundColor";
    this.atributo=atributo
    this.elemento=elemento;
    this.inicio=inicio;
    this.fin=fin;
    this.tiempo=tiempo;
    this.inicioR=parseInt(inicio.substr(0,2),16);
    this.inicioG=parseInt(inicio.substr(2,2),16);
    this.inicioB=parseInt(inicio.substr(4,2),16);
    this.finR=parseInt(fin.substr(0,2),16);
    this.finG=parseInt(fin.substr(2,2),16);
    this.finB=parseInt(fin.substr(4,2),16);
    
    intervalo=50;
    
    this.timer=null;
    
    this.colorR=this.inicioR;
    this.colorG=this.inicioG;
    this.colorB=this.inicioB;
    
    this.incrementoR=(this.finR-this.inicioR)*intervalo/tiempo; 
    this.incrementoG=(this.finG-this.inicioG)*intervalo/tiempo; 
    this.incrementoB=(this.finB-this.inicioB)*intervalo/tiempo; 
    
    this.over=function(){
        // printfire((new Date).getSeconds()+" "+(new Date).getMilliseconds());
        var self=this;
        window.clearInterval(self.timer);
        self.timer=window.setInterval(function(){
            self.colorR+=Math.round(self.incrementoR);
            self.colorG+=Math.round(self.incrementoG);
            self.colorB+=Math.round(self.incrementoB);
            if ( (self.colorR>=self.inicioR && self.colorR>=self.finR || self.colorR<=self.inicioR && self.colorR<=self.finR) ){
                self.colorR=self.finR;
                self.colorG=self.finG;
                self.colorB=self.finB;
                window.clearInterval(self.timer);
                // printfire((new Date).getSeconds()+" "+(new Date).getMilliseconds());
            }
            self.elemento.style[self.atributo]='rgb('+self.colorR+','+self.colorG+','+self.colorB+')';  
        },intervalo); 
    }

    this.out=function(){
        var self=this;
        window.clearInterval(self.timer);
        self.timer=window.setInterval(function(){
            self.colorR-=Math.round(self.incrementoR);
            self.colorG-=Math.round(self.incrementoG);
            self.colorB-=Math.round(self.incrementoB);
            if ( (self.colorR<=self.inicioR && self.colorR<=self.finR || self.colorR>=self.inicioR && self.colorR>=self.finR) ){
                    self.colorR=self.inicioR;
                    self.colorG=self.inicioG;
                    self.colorB=self.inicioB;
                    window.clearInterval(self.timer);
            }
            self.elemento.style[self.atributo]='rgb('+self.colorR+','+self.colorG+','+self.colorB+')';    
        },intervalo);
    }
    
}


function colorearTablas(){
    tablas=document.getElementsByTagName('table');
    for(var k=0;k<tablas.length;k++){
        trs=tablas[k].getElementsByTagName('tr');
        for(var q=0;q<trs.length;q++){
            if( (q%2)==0)
                trs[q].className='fila_sin_color';  
            else
                trs[q].className='fila_color';
        }
    }  
}



