// Variables globales
var fechaServidorInicial = new Date();
var serverDate;
var horas, minutos, segundos;

	function sumaSegundos() {
		if (segundos < 59) {
		    segundos++;
		} else {
			segundos = 0;
			sumaMinutos();
		}
	}
	
	function sumaMinutos() {
	    if (minutos < 59) {
	        minutos++;
	    } else {
	        minutos = 0;
	        sumaHoras();
	    }
	}
	
	
	function sumaHoras() {
		if (horas < 23) {
		    horas++;
		} else {
		    horas = 0;
		}
	}

	 // Usada solo en depuración para ver lo que pinta.
	/*
	function pintaHora() {
		sumaSegundos();
	    var spanReloj = document.getElementById('reloj');
	    spanReloj.innerHTML = horas + " : " + minutos + " : " + segundos;
	}
	*/

	// Pasarle por parámetro '<?= date('F d, Y H:i:s') ?>'
	function inicializarHoraServer(fechaPhp) {
	    serverDate = new Date(fechaPhp); // Hora del server
        horas = serverDate.getHours();
        minutos = serverDate.getMinutes();
        segundos = serverDate.getSeconds(); 
	}
	/*function inicializarHoraServer() {
	    serverDate = new Date(); // Hora del server
        horas = serverDate.getHours();
        minutos = serverDate.getMinutes();
        segundos = serverDate.getSeconds(); 
	}*/

    // Devuelve la hora del servidor actualizada.
	function getHoraServerActualizada() {
		sumaSegundos();
		serverDate.setHours(horas, minutos, segundos, 0);
	}
	
	
	
	var nombreEvento = "";	
	var idEvento = "";
	function calcularDiferencia(arrGrupoEventos) {
		
		var diferencia;
		var fechaEvento;
		
		// Recorremos el grupo de eventos para obtener el que mas se aproxime a la hora actual.
		for ( var i = 0; i < arrGrupoEventos.length; i++) {
			fechaEvento = new Date();
		    fechaEvento.setHours(arrGrupoEventos[i][0]);
		    fechaEvento.setMinutes(arrGrupoEventos[i][1]);
		    fechaEvento.setSeconds(arrGrupoEventos[i][2]);
		    
		    // Cuando diferencia sea positivo nos quedamos con ese
		    // Esto obliga a que los eventos sean listados en orden cronológico.
		    
		    diferencia = (fechaEvento.getTime() -  serverDate.getTime()) / 1000;	
		    
		    if (diferencia > 0) {
		    	nombreEvento = arrGrupoEventos[i][3];		    	
		    	idEvento = arrGrupoEventos[i][4];
		    	return diferencia;
		    }
		}
	}
	
	function mostrarMensajeDiferencia(diferencia) {
		
		var txtRetorno = "";
		nombreEvento = "<b>" + nombreEvento + "</b>";
		// 300 segundos = 5 min tiempo de cortesía para entrar 
	    if (diferencia >= 0 && diferencia < 300) 
		{
	   		txtRetorno = '<font  style="color: #00FF00 !important">' + nombreEvento + ': Abierto !! </font>';
	    }  
		else if (diferencia < 0) 
		{
	        // Se ha pasado.
	    	txtRetorno = nombreEvento + ': Mañana';
	    } 
		else {
	        dia= Math.floor(diferencia/60/60/24);
	        hora= Math.floor((diferencia - dia*60*60*24)/60/60);
	        minuto= Math.floor((diferencia - dia*60*60*24 - hora*60*60)/60);
	        segundo= Math.floor(diferencia - dia*60*60*24 - hora*60*60 - minuto*60);
	        txtRetorno = '' + nombreEvento + ': ';               
	        if (hora > 0 || dia > 0) {
	        	txtRetorno+=hora+' h';
	            if (hora != 1) { txtRetorno+='s'; }
	            txtRetorno+= ' ';
	        }
	        if (minuto > 0 || hora > 0 || dia > 0) {
	        	txtRetorno+=minuto+' m';
	            if (minuto != 1) { txtRetorno+='s'; }
	            txtRetorno+= ' ';
	        }
	     
	      // Comentamos los segundos ( si son innecesarios )
	        txtRetorno+=segundo+' s';
	        if (segundo != 1) { 
	        	txtRetorno+='s'; 
	        }
	        
	    }
	    
	    return txtRetorno;
	}
	
	
	function actualizadorContadorEventos() {
		var dif;
		for ( var i = 0; i < arrGrupoEventos.length; i++) 
		{			
			dif = calcularDiferencia(arrGrupoEventos[i]);
			if(dif>0) 
			{
				document.getElementById('spEvent' + idEvento).innerHTML = mostrarMensajeDiferencia(dif);
			}
		}
	}
	
	
	
	// Pinta la tabla con los id de TR para luego ir pintando las horas.
	function pintarEventosFirstTime() {
	    var numeroEventos = arrGrupoEventos.length ;
	    var capa = document.getElementById('idSpanEventos');
	    var tablaTxt = "";
	    tablaTxt += "<table border='0' width='163'>";          
	    
	    
	        for ( var i = 0; i < numeroEventos; i ++ ){
	            tablaTxt += "       <tr> ";
	            tablaTxt += "           <td> ";
	            tablaTxt += "            <span style='font-family: Tahoma;font-size: 9px;' id='spEvent" + arrGrupoEventos[i][0][4] + "' />";
	            tablaTxt += "           </td> ";
	            tablaTxt += "       </tr> ";
	        }
	            
	        tablaTxt += "</table>";
	                
	        capa.innerHTML = tablaTxt;
	}
