﻿// JScript File
var timeout;
var timeoutDia;
var ListaAbierta;
var posScrollDivAbierto;

function CambioDia(tiempo){
    if ( tiempo> 0) {
         window.clearTimeout(timeoutDia);
         timeoutDia=window.setTimeout('CambiarContenido("Primero", 86400000);', (parseInt(tiempo)+1000));
         //86400000 = 24 horas.
    }
}

/******************************************************/
/* funciones que obtienen la programación y la pintan */
/******************************************************/
function CambiarContenido_CallBack(response){
    var datos; 
    var tiempo;
    var ds = response.value;

    window.clearTimeout(timeout);

    if(response.error == null) {
        if (ds != null && typeof(ds) == "string"){
            datos=ds.split('~');
           
            document.getElementById('Descripcion').innerHTML =datos[3];
            //Colocamos después para que primero se pinte la descripción;
            document.getElementById('imgPrimero').src=datos[0];     
            document.getElementById('imgSegundo').src=datos[1];
            document.getElementById('imgTercero').src=datos[2];
            
            tiempo =  datos[4]; 
            
            PosicionScroll();
            
            
             /* el tiempo > 0 cuando estamos en el día actual */       
            if ( tiempo> 0) { timeout=window.setTimeout('VolverPintar();', (parseInt(tiempo)+1000));}
           
        }
        else
            document.location='paginaError.aspx';        
   }
   else
        document.location='paginaError.aspx';        
}
 
function CambiarContenido(link, tiempo){

    document.getElementById('imgPrimero').className = 'lineaverde' ;
    document.getElementById('imgSegundo').className = 'lineaverde' ;
    document.getElementById('imgTercero').className = 'lineaverde' ;
    
    document.getElementById('spPrimero').style.width = '96px' ;
    document.getElementById('spSegundo').style.width = '95px' ;
    document.getElementById('spTercero').style.width = '94px' ;
   
   
    document.getElementById('spPrimero').style.backgroundColor = '#a9c215' ;
    document.getElementById('spSegundo').style.backgroundColor = '#a9c215' ;
    document.getElementById('spTercero').style.backgroundColor = '#a9c215' ;
    document.getElementById('sp' + link).style.backgroundColor = '#1a171b' ;
    document.getElementById('sp' + link).style.width = '91px' ;
    
    
    
      //inicializamos las variables:
    ListaAbierta=false;
    DivMarcado=null;
    posScrollDivAbierto=0;
                
    document.getElementById('img'+link).className = '' ;
    
    contenido = inicio.GetContenido(link, CambiarContenido_CallBack); 
    CambioDia(tiempo);   
}

/*--------------------------------------------------------------------*/ 

/* SÓLO cambia la programación, no el estado de las pestañas.
   SÓLO se llama a esta función si estamos en el dia actual.*/  
function VolverPintar(){
    contenido = inicio.GetVolverPintar(VolverPintar_CallBack); 
}

function VolverPintar_CallBack(response) {
    var datos;
    var tiempo; 
    var ds = response.value;

    window.clearTimeout(timeout);

    if(response.error == null) {    
        if (ds != null && typeof(ds) == "string"){
            datos=ds.split('~');
            document.getElementById('Descripcion').innerHTML =datos[0];
            
            //Ponemos la lista abierta o no en función del tiempo
            if (ListaAbierta==true){
                MostrarDiv(DivMarcado);
                //document.getElementById('ctl00_MainContent_pnlProgramacion').scrollTop=posScrollDivAbierto;
            }
            else {
                 PosicionScroll();
                 }
            
            tiempo =  datos[1]; 
             if ( tiempo > 0) {timeout=window.setTimeout('VolverPintar();', (parseInt(tiempo)+1000));}
        }
       else
            document.location='paginaError.aspx';   
    } 
    else
      document.location='paginaError.aspx';      
}

 /******************************************************/    
/* eventos en la parrilla de programación */
/******************************************************/
    
function AbrirVideo(url){
   
        document.location='Visualizacion/Visualizar.aspx?VidID='+url;
  
}   
  
function MostrarDiv(valA){
    if ($(valA)[0]!=null){                 
        if ($(valA)[0].style.display=='none'){                    
            ListaAbierta=true;
            DivMarcado=valA;
            
            //Guardamos la posicion del scroll abierto;
            //posScrollDivAbierto=document.getElementById('ctl00_MainContent_pnlProgramacion').scrollTop;
            
            $(".Programa").hide();               
            $(valA).show('fast');
        }
        else {
            ListaAbierta=false;
            $(valA).hide('fast');   
            }
    }
}

/* si la imagen contiene "_sel" es porque está seleccionada. 
        si imagen seleccionada -> no se modifica la imagen
        eoc                    -> se cambia la imagen por la que termina en "_sel" */
function CambiaImagenOver(e){
    var srcEl = e.srcElement? e.srcElement : e.target; 
  
  
    if (srcEl.src.indexOf('_sel') == -1 ) {
        var index;
        var ruta;
        index = srcEl.src.indexOf('.gif');
        ruta = srcEl.src.substring(0, index);
        if (ruta !=''){
            srcEl.src = ruta+'_sel.gif';
        }		
    }
}
/* si la imagen tiene estilo es porque NO está seleccionada.
        si imagen no tiene estilo -> no se modifica la imagen
        eoc                       -> se cambia la imagen por la que NO tiene "sel" */
function CambiaImagenOut(e){
    var srcEl = e.srcElement? e.srcElement : e.target; 
  
    var elem;
    elem= document.getElementById(srcEl.id);
    if (elem.className != '')  {
        var index;
        var ruta;
        index = srcEl.src.indexOf('_sel.gif');
        ruta = srcEl.src.substring(0, index);
        if (ruta !=''){
            srcEl.src = ruta+'.gif';
        }
    }
}


function PosicionScroll(){
    var strContenido;
    var posiSelect;
    var posiSelectFin;
    var strContenidoMin;

    //debugger;

    strContenido=document.getElementById('ctl00_MainContent_pnlProgramacion').innerHTML;

    posiSelect=strContenido.indexOf('progSelect');
    
    if (posiSelect!=-1){
    
            posiSelectFin=strContenido.indexOf(' ', posiSelect + 22);
    
            strContenidoMin = strContenido.substring(posiSelect + 22, posiSelectFin);
          
            var scrollT=(strContenidoMin-1)*33;
           
            document.getElementById('ctl00_MainContent_pnlProgramacion').scrollTop=scrollT;
    
    
    }

}

/****************************************************************************************/    
/* funciones para mostrar y ocultar la capa con los datos de informacion de un video    */
/****************************************************************************************/


function MostrarCapa(indice){
//debugger;
    if(document.getElementById('divInfoVideo' + indice)!=null){
        $("div#divInfoVideo" + indice).show("fast");
    }
}

function OcultarCapa(evento,indice){

//debugger;
    //calcula la posicion en la que esta el puntero del raton
    //si esta fuera de los limites que ocupan la imagen + la capa de datos del video 
    //entonces se oculta

    //Nota: para que funcione en los distintos navegadores usamos la propiedad parentNode en lugar de parentElement que solo existe en ie
    
    if(document.getElementById('divInfoVideo' + indice)!=null){

        //calcular la altura superior a la que esta la imagen (quitamos 2px para asegurarnos que el raton queda dentro de los margenes) 
        var PosYCapa = document.getElementById('divInfoVideo' + indice).parentNode.offsetTop;
        var altoImagen = document.getElementById('ctl00_MainContent_img' + indice).height;
        var altoTit = document.getElementById('ctl00_MainContent_tit' + indice).parentNode.offsetHeight

        var top = PosYCapa - altoTit - altoImagen ; 

        //calcular la altura inferior a la que esta la capa (quitamos 2px para asegurarnos que el raton queda dentro de los margenes) 
        var up = PosYCapa + document.getElementById('divInfoVideo' + indice).clientHeight - 2;
        
        // calcular el margen izq (sumamos 2px para asegurarnos que el raton queda dentro de los margenes) 
        var left = document.getElementById('divInfoVideo' + indice).parentNode.offsetLeft + 2; 

        // calcular el margen drcho (quitamos 2px para asegurarnos que el raton queda dentro de los margenes) 
        var der = document.getElementById('divInfoVideo' + indice).parentNode.offsetLeft + document.getElementById('ctl00_MainContent_img' + indice).width - 2;
      
        //capturar el evento del raton, se hace distincion para que funcione con los distintos navegadores
        //para ie se obtiene con window.event para el resto el que se pasa por parametro a la funcion
        var mouse = evento || window.event;

        //recuperar las coordenadas de la posicion del raton, el origen se encuentra en la esquina superior izquierda
        //pero el origen puede variar dependiendo del que se tome como referencia:
        //respecto del origen de la ventana del navegador, respecto del origen de la pagina(es el que usare) y
        //respecto de la pantalla completa del ordenador
        
        // como las coordenas son respecto al origen de la pagina tenemos que sumarle el scroll
        posX = mouse.clientX + document.body.parentNode.scrollLeft;
        posY = mouse.clientY + document.body.parentNode.scrollTop;

        //window.alert("OcultarCapa posX: " + posX + " posY: " + posY + " izq: " + left + " der: " + der + " top: " + top + " up: " + up );

        //si la posicion del raton esta fuera de los margenes top,up,left y der de la imagen+capa la ocultamos
        if ((posX <= left) || (posX >= der) || (posY <= top) || (posY >= up) || (posX < 0) || (posY < 0)){
            $("div#divInfoVideo" + indice).hide("fast");
        }   
    }
}

