var lTimerCambioCanal = null;
var lTimerTeclaCambio = null;

var iNumCanal = -1;
var CFG_CANAL = "cfg.canal";

var indi=0;
var MAX_CELDAS=96;

function Pag_Canal_Show(iCan, bForzar) {
	
	var cIPDir = "";
	var dAhora= new Date();
	
	// Si no tiene una hora correcta intenta ponerla del TDT
	if (getToken(CFG_ModoRed, DEF_ModoRedStatic) == DEF_ModoRedStatic) 
	{
		cIPDir = getToken(CFG_DirEquipo, DEF_DirEquipo);
	}
	else cIPDir="192.168.1.10";

	try {
				if (dAhora<1000000 && ialEnv.dvbTuners.item(0).status>-1) // Si no tiene una hora correcta intenta ponerla del TDT
					{
						SendMsg2("TIME " + ialEnv.dvbTuners.item(0).time,cIPDir);
					}
		iLastKeyChar = -1;
		iModoPlay = 0;
		if ((iNumCanal != iCan) || bForzar) {
			try {
				objVideo.close();
			} catch(ex) {}

			iNumCanal = iCan;
			if (iNumCanal > objTuner.services.length) iNumCanal = 1;
			if (iNumCanal < 1) iNumCanal = objTuner.services.length;

			var objCanal = ObtenerCanal(iNumCanal);
			objVideo.open(objCanal.serviceInfo.uri, null);
			setValue(CFG_CANAL, iNumCanal);
		} else {
			var objCanal = ObtenerCanal(iNumCanal);
		}	
		var celda,i,c2;
		
		if (objCanal.events.length==2) 
			{
				c2= '<tr height="23px">'
			+'							<td id="Pag_Canal_Evento1" colspan="3"  bgcolor="#0D428F" width="500px" class="font15" style="white-space: nowrap; text-overflow: clip; ellipsis: hidden;"></td>'
			+'							<td width="20px" bgcolor="#0D428F"/>'
			+'		 </tr>';
			}
		else {c2=''; }

		celda='';
		for (i=1; i<=MAX_CELDAS;i++ )
			celda= celda + '<td id="p' + i + '" cellspacing="0"  style="z-index:0;border:none;border-left:0px;" height="30px" width="' + parseInt(480/MAX_CELDAS) + 'px" borderColor="#0000FF"></td>'
		Page_Show("Pag_Canal", 
			'<div id="Barra_estado" style="position:absolute;top:491px;left:86px;width:500px; height:23px; overflow:auto; border:1px solid #000">'
			+'<table border="0px" cellspacing="0" >'
			+'<tr>'
			+ celda
			+'</tr>'
			+'</table>'
			+'</div>'
			+'<table width="720px" cellpadding="0" cellspacing="0" style="position: absolute;">'
			+'<tr height="453px"/>'
			+'<tr height="67px">'
			+'	<td width="55px"/>'
			+'	<td width="590px" height="67px">'
			+'		<table width="550px" height="67px" cellpadding="0" cellspacing="0" style="table-layout: fixed">'
			+'			<tr height="33px" bgcolor="#4A72C5"><td width="30px"/><td width="30px" class="font15" id="Pag_Canal_NumCanal">' + iNumCanal + '</td><td width="280px" class="font15" id="Pag_Canal_Nombre">' + objCanal.name + '</td><td align="right" class="font15">' + ObtenerHoraActual() + '</td></tr>'
			+'			<tr height="33px">'
			+'				<td width="30px" bgcolor="#0D428F"/>'
			+'				<td colspan="3" >'
			+'					<table id="tinfo2" height="33px" cellpadding="0" cellspacing="0" style="table-layout:fixed;">'
			+'						<tr height="6px"><td bgcolor="#0D428F" width="20px"/><td bgcolor="#0D428F" width="480px" colspan="2"/><td bgcolor="#0D428F" width="20px"/></tr>'
			+'						<tr height="23px">'
			+'							<td id="Pag_Canal_Evento0" colspan="3" width="500px" class="font15" style="white-space: nowrap; text-overflow: clip; ellipsis: hidden;"></td>'
			+'							<td width="20px" bgcolor="#0D428F"/>'
			+'						</tr>'
			+'						<tr height="6px"><td colspan="4" bgcolor="#0D428F"></td></tr>'
			+ c2 +'					</table>'
			+'				</td>'
			+'			</tr>'
			+'		</table>'
			+'	</td>'
			+'	<td width="55px"/>'
			+'</tr>'
			+'</table>');

		RefreshCanalShow2(1);
		lTimerPageHide = setTimeout("Page_Show('', '')",5000);
	} catch(ex) {
		alert("Pag_Canal_Show: " + ex);
	}
}

function Pag_Canal_Hide() {
	if (lTimerCambioCanal != null) {
		clearTimeout(lTimerCambioCanal);
		lTimerCambioCanal = null;	
	}
	if (lTimerTeclaCambio != null) {
		clearTimeout(lTimerTeclaCambio);
		lTimerTeclaCambio = null;	
	}
}

function RefreshCanalShow2(iRetry) 
{
	var objCanal = ObtenerCanal(iNumCanal);
	try {
		var iHoras;
		var iMinutos;
		var objEvento;
		var dAhora;
		var dFin;
	
		for (var i=0; i < objCanal.events.length; i++)
		{ 
			if (i==0) objEvento = objCanal.events.getPresentEvent();
			else objEvento = objCanal.events.item(i);
			dAhora = new Date();
			dFin = new Date((objEvento.startTime + objEvento.duration) * 1000);
   		if (dFin >= dAhora) 
   		{ 
   			var dInicio = new Date(objEvento.startTime * 1000);
   			iHoras = dInicio.getHours();
   			iMinutos = dInicio.getMinutes();
   			var cHoraInicio = ((iHoras<10)?"0":"") + iHoras + ":" + ((iMinutos<10)?"0":"") + iMinutos;
   			iHoras = dFin.getHours();
   			iMinutos = dFin.getMinutes();
   			var cHoraFin = ((iHoras<10)?"0":"") + iHoras + ":" + ((iMinutos<10)?"0":"") + iMinutos;
   			document.getElementById("Pag_Canal_Evento" + i).innerHTML = cHoraInicio + "-" + cHoraFin + "  " + objEvento.name.substr(0,38);
   			if (i==0) Pon_BarraTiempo(dInicio,dAhora,dFin);
   			
   		} else if (iRetry < 15) {
   			lTimerCambioCanal = setTimeout("RefreshCanalShow2(" + (iRetry+1) + ")", 300);
   		}
	  }/*del for i*/
	 } catch(ex) {
		/* Si no se ha encontrado evento actual, retardar un poco la actualizacion en pantalla de la información */
		if (iRetry < 15) 
		{
			lTimerCambioCanal = setTimeout("RefreshCanalShow2(" + (iRetry+1) + ")", 300);
			document.getElementById("Pag_Canal_Evento0").innerHTML = "INFORMACION NO PROPORCIONADA por el operador TV";
		}
		else
			{
				document.getElementById("Pag_Canal_Evento0").innerHTML = "INFORMACION NO PROPORCIONADA por el operador TV";
			}
	}
	if (objCanal.events.length ==0) 
		{
			lTimerCambioCanal = setTimeout("RefreshCanalShow2(" + (10+1) + ")", 300);
			document.getElementById("Pag_Canal_Evento0").innerHTML = "INFORMACION NO PROPORCIONADA por el operador TV";
			document.getElementById("Pag_Canal_Evento0").bgColor="#4A72C5";
		}
}


function RefreshCanalShow(iRetry) {
	var objCanal = ObtenerCanal(iNumCanal);
	try {
		var iHoras;
		var iMinutos;
		var objEvento = objCanal.events.getPresentEvent();
		var dAhora = new Date();
		var dFin = new Date((objEvento.startTime + objEvento.duration) * 1000);
		
		if (dFin >= dAhora) { 
			var dInicio = new Date(objEvento.startTime * 1000);
			iHoras = dInicio.getHours();
			iMinutos = dInicio.getMinutes();
			var cHoraInicio = ((iHoras<10)?"0":"") + iHoras + ":" + ((iMinutos<10)?"0":"") + iMinutos;
			iHoras = dFin.getHours();
			iMinutos = dFin.getMinutes();
			var cHoraFin = ((iHoras<10)?"0":"") + iHoras + ":" + ((iMinutos<10)?"0":"") + iMinutos;
			document.getElementById("Pag_Canal_Evento0").innerHTML = cHoraInicio + "-" + cHoraFin + "  " + objEvento.name.substr(0,38);
			Pon_BarraTiempo(dInicio,dAhora,dFin);
			
		} else if (iRetry < 15) {
			lTimerCambioCanal = setTimeout("RefreshCanalShow(" + (iRetry+1) + ")", 300);
		}
	} catch(ex) {
		/* Si no se ha encontrado evento actual, retardar un poco la actualizacion en pantalla de la información */
		if (iRetry < 15) 
		{
			lTimerCambioCanal = setTimeout("RefreshCanalShow(" + (iRetry+1) + ")", 300);
			document.getElementById("Pag_Canal_Evento0").innerHTML = "INFORMACION NO PROPORCIONADA por el operador TV";
		}
		else
			{
				document.getElementById("Pag_Canal_Evento0").innerHTML = "INFORMACION NO PROPORCIONADA por el operador TV";
			}
	}
}



function Pon_BarraTiempo(dInicio,dAhora,dFin)
{
	var ahora1, ini1,fin1;
	
	ahora1=dAhora.getHours()*3600+dAhora.getMinutes()*60+dAhora.getSeconds();
	ini1=dInicio.getHours()*3600+dInicio.getMinutes()*60+dInicio.getSeconds();
	fin1=dFin.getHours()*3600+dFin.getMinutes()*60+dFin.getSeconds();
			if ( (dFin.getDay() != dAhora.getDay()) || (dInicio.getDay() != dAhora.getDay()) )
				{
					if (dFin.getDay() == dAhora.getDay()) // actual y final en el mismo dia
						{
							ahora1=ahora1+86400;
							fin1= fin1+86400;
						}
					else // el final es distinto dia
						{
							fin1= fin1+86400;
					  }
				}
	//alert(ini1 + '  '+ ahora1 + ' ' + fin1);
	ini1=parseInt(ahora1-ini1)*MAX_CELDAS/(fin1-ini1);
	
	for (fin1=1; fin1<=ini1; fin1++)
		document.getElementById('p'+fin1).bgColor="#4A72C5";
}


function Pag_Canal_KeyDown(keyChar) {
	try {
		switch (keyChar) {
		case KEY_UP:
		case KEY_CHUP:
			Pag_Canal_Show(iNumCanal + 1, false);
			return 0;
		case KEY_DOWN:
		case KEY_CHDN:
			Pag_Canal_Show(iNumCanal - 1, false);
			return 0;
		case KEY_0: case KEY_1:
		case KEY_2: case KEY_3:
		case KEY_4: case KEY_5:
		case KEY_6: case KEY_7:
		case KEY_8: case KEY_9:
			if (iLastKeyChar == -1) {
				Pag_Canal_Show(iNumCanal, false);
				iLastKeyChar = keyChar;
				lTimerTeclaCambio = setTimeout("Pag_Canal_Show(" + (iLastKeyChar  - KEY_0) + ", false)", 1000);
				document.getElementById("Pag_Canal_NumCanal").innerHTML = (iLastKeyChar  - KEY_0) + "|";
			} else {
				Pag_Canal_Show((iLastKeyChar  - KEY_0) * 10 + keyChar - KEY_0, false);
			}
			return 0;
		case KEY_HELP:
			Pag_Canal_Show(iNumCanal, false);
			return 0;
		case KEY_BACK:
			Page_Show("", "");
			return 0;
		case KEY_WWW:
			var miFecha = new Date();
			var dato_url = miFecha.getYear().toString() + miFecha.getMonth().toString() + miFecha.getDate().toString() + miFecha.getHours().toString() + miFecha.getMinutes().toString() + miFecha.getSeconds().toString();
			setTimeout("window.location='mediacenter.html?parametro=" + dato_url + "'", 1000);
			return 0;
		case KEY_TV:
		case KEY_GUIATV:

			Page_Show("Pag_EPG",
		 '<table width="719px" cellpadding="0" cellspacing="0" style="position: absolute; table-layout: fixed; background-image: url(fondo_datos.png);">'
		+'<tr height="88px">'
		+	'<td width="75px"/>'
		+	'<td width="220px" valign="bottom" style="color:#ffffff; font-size:18pt;">EPGar canales</td>'
		+	'<td width="280px" valign="bottom" align="right" class="font15"> '+ ObtenerHoraActual() + '</td>'
		+	'<td width="140px"/>'
		+'</tr>'
		+'<tr height="17px"/>'
		+'<tr height="34px"><td/><td class="font16">&nbsp;<u>Eventos</u></td><td class="font16"><u>' + ' Sin Nombre' + '</u></td></tr>'
		+'<tr height="315px">'
		+	'<td/>'
		+	'<td valign="top" colspan="3">'
		+	'<table id="Frm_EPG" width="570px" cellpadding="0" cellspacing="0" style="table-layout: fixed">'
		+		'<tr height="34px" id="Pag_EPG_Opcion1" style="background-repeat: no-repeat;">'
		+   '<td id="Pag_EPG_Horas1" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento1" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion2" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas2" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento2" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion3" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas3" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento3" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion4" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas4" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento4" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion5" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas5" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento5" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion6" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas6" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento6" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion7" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas7" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento7" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion8" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas8" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento8" width="430px" class="font16"></td><td width="50px"/></tr>'
		+		'<tr height="34px" id="Pag_EPG_Opcion9" style="background-repeat: no-repeat;"><td id="Pag_EPG_Horas9" align="right" width="80px" class="font16"></td><td id="Pag_EPG_Evento9" width="430px" class="font16"></td><td width="50px"/></tr>'
		+	'</table>'
		+	'</td>'
		+'</tr>'
		+'<tr height="50px" valign="top"><td/><td class="font16" style="background-image: url(boton_rojo.png); background-repeat: no-repeat;"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Guardar</td><td class="font16" style="background-image: url(boton_azul.png); background-repeat: no-repeat;"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Cancelar</td></tr>'
		+'<tr height="50px"/>'
		+'</table>');
		Pag_EPG_Show(0);
			return 0;
		}
	} catch(ex) {
		alert("Pag_Canal_KeyDown: " + ex);
	}
	return 1;
}


function CreateTransport2(cIP) 
{
	var iPort = getValue(CFG_PuertoServidor, DEF_PuertoServidor);

	try {
		if (socket != null) {
			if (socket.isAlive()) {
				cIP = "";
			}
		}
	} catch(ex) {
		alert("SendMsg1: " + ex);
	}

	if (cIP > "") {
		try {
			outstream.close();
		} catch(ex) {}

		try {
 		 	instream.close();
		} catch(ex) {}

		try {
			socket.close(0);
		} catch(ex) {}
		try {
			socket = transportService.createTransport(null, 0, cIP, iPort, null);
		} catch(ex) {
			alert("SendMsg2: " + ex);
		}
		try {
			outstream = socket.openOutputStream(0,0,0);
		} catch(ex) {
			alert("SendMsg3: " + ex);
		}
		try {
			instream = socket.openInputStream(0,0,0); // OPEN_BLOCKING =1
	    		inscrpstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
	      			.createInstance(Components.interfaces.nsIScriptableInputStream);
		    	inscrpstream.init(instream);
		} catch(ex) {
			alert("SendMsg4: " + ex);
		}
	}

}

function SendMsg2(cMsg, cIP) 
{
	try {
		CreateTransport2(cIP);
	} catch(ex) {
		alert("SendMsg2: " + ex);
	}
	try {
		outstream.write(cMsg + String.fromCharCode(0),cMsg.length + 1);
	} catch(ex) {
		alert("SendMsg3: " + ex);
	}
}