/**
 * Proyecto		RT-GUI Plataforma de tiempo real para decodificadores basados en browser
 * Modulo		core/VideoObject_TOI.js ... driver de Video para descos OIS/IAL 1.1 compliant
 * Autor		Rodolfo López Pintor, 2004
 */

/////////////// setVideoConfig

	top._startAudio=null;
	top._startTime=null;

	top.setVideoConfig=function(time, audio) {
		top._startTime=time;
		top._startAudio=audio;
	}
	top.executeVideoConfig=function() {
		try {
			top.Video.videoPlayer.play (1000, (top._startTime!=null?top._startTime:-1), -1);
			top.Video.state=top.Video.STATUS_VOD_PLAY;
		} catch (e) {}
	}
	top.destroyRec_channel=function(tecla){
		if(tecla=="red"){
			top.Video.videoRecorder.scheduled.item(0).destroy();
			top.Video.recordingIPchannel=false;
		}else{
			var recordedChannel=parseInt(top.Video.videoRecorder.scheduled.item(0).label.substr(1,3));
			if(top.sysStatus==top.ST_TV){
				queueChangeCanal(getChannelIndex(recordedChannel));
			}else{
				minitv_queueChangeCanal(getChannelIndex(recordedChannel));
			}
		}
	}
	top.destroyRec_vod=function(tecla){
		if(tecla=="red"){
			top.Video.videoRecorder.scheduled.item(0).destroy();
			top.Video.recordingIPchannel=false;
		}else{
			top.pane.keyPressed(top.KEY_STOP);
		}
	}
	top.videoListener=function(ev) {
		switch (ev.type) {
			case top.Video.videoPlayer.ON_STATE_CHANGED :
				switch (ev.state) {
					case top.Video.videoPlayer.STATE_CONNECTING:
						// Hemos recibido un STATE_CONNECTING
						// a continuación recibiremos un STATE_PAUSED
						// y habrá que poner a andar la movida
						top._lstat=true;
						break;
					case top.Video.videoPlayer.STATE_PAUSED:
					case top.Video.videoPlayer.STATE_PAUSED_RECORDING:
						switch (ev.reason) {
							case top.Video.videoPlayer.REASON_POSITION_EDGE:
								//if (top.Video.event_Edge) try { top.Video.event_Edge((ev.code==2101?1:0)); } catch (e) {}
								top.Video.velocidad = 0;
								mostrarControl(2);
								break;
							default:
								top._lstat=false;
								try { executeVideoConfig(); } catch (e) { Debug (e.description); }
						}
						break;
					case top.Video.videoPlayer.STATE_PLAYING:
					case top.Video.videoPlayer.STATE_PLAYING_RECORDING:
						switch (ev.reason) {
							case top.Video.videoPlayer.REASON_POSITION_EDGE:
								//if (top.Video.event_Edge) try { top.Video.event_Edge(1); } catch (e) {}
								top.Video.velocidad = 1000;
								mostrarControl(1);
								break;
						}
						break;
					case top.Video.videoPlayer.STATE_FAILED:
						if (top._lstat) {
							
						}
						try { top.Video.event_Failed(); } catch (e) {}
						break;
					default:
						
						_lstat=false;
						break;
				}
				break;
			default:
				_lstat=false;
		}
	}
	top.streamListener=function(ev) {
		if (top._startAudio!=null) top.Video.setAudioStream(top._startAudio);
	}
	top.recordListener=function(ev){
		switch (ev.type) {
			case top.Video.videoRecorder.ON_STATE_CHANGED :
				switch (ev.newstate) {
					case top.Video.videoRecorder.RECORDING_LIST:
						if (ev.oldstate==top.Video.videoRecorder.PENDING_LIST){
							//A recording has started
							var duration=top.Video.videoRecorder.running.item(0).length;
							var minutes=Math.floor(duration/60);
							var hours=Math.floor(minutes/60);
							if(hours>0) minutes=minutes%60;
							var seconds=duration%60;
							var duration_time=(hours>0?hours+"h. ":"")+minutes+"m.";
							//top.warning(top._GLOC("dvr.startrec")+': "'+top.Video.videoRecorder.running.item(0).label.substr(1)+'". '+top._GLOC("dvr.durationrec")+': '+duration_time,new Array(null,top._GLOC(5,121),null,null),null,false);
							for(i=0; i<top.Video.videoRecorder.running.length; i++) {
								if (top.Video.videoRecorder.running.item(i).sourceurl.substring(0,6)== "dvb://")
									runDTT += 1;
							//if(runDTT ==2)
								//Video.setChannel(Video.videoRecorder.running.item(0).sourceurl, "none");
							/*if(!top.Video.recordingIPchannel){
								for(i=0;i<top.Video.videoRecorder.running.length;i++){
									if(top.Video.getUrlRecordType(top.Video.videoRecorder.running.item(i).sourceurl)=="1"){
										top.Video.recordingIPchannel=true;
										break;
									}
								}*/
							} 
						}
						break;
					case top.Video.videoRecorder.PENDING_LIST:
						if (ev.oldstate==top.Video.videoRecorder.PENDING_LIST){
							try{
								if((runDTT==1) && (top.Video.videoRecorder.scheduled.sourceurl.substring(0,6)== "dvb://")) {
									warning(1);
									Video.setChannel(Video.videoRecorder.running.item(0).sourceurl, "none");
								}
								else
								{
									warning(0);
									try{ top.Video.videoPlayer.setParameter("shifttv","auto");}catch(e){}
								}
							}catch(e1){}
						}
						break;
					case top.Video.videoRecorder.STORED_LIST:
						if (ev.oldstate==top.Video.videoRecorder.RECORDING_LIST){
							//A recording has finished
							//top.warning(top._GLOC("dvr.finrec")+': "'+top.Video.videoRecorder.stored.item(top.Video.videoRecorder.stored.length-1).label.substr(1)+'"',new Array(null,top._GLOC(5,121),null,null),null,false);
					/*		var channelType=top.Video.getActualChannelType();
							if((top.Video.shifttvState()!="auto")&&(channelType=="1" || channelType=="4")&&(top.Video.mode=="FULL"))
								try{ top.Video.videoPlayer.setParameter("shifttv","auto");}catch(e){}
							if(top.Video.recordingIPchannel)
								if(top.Video.getUrlRecordType(top.Video.videoRecorder.stored.item(top.Video.videoRecorder.stored.length-1).sourceurl)=="1")
									top.Video.recordingIPchannel=false;
					*/
							if(top.Video.videoRecorder.stored.item(top.Video.videoRecorder.stored.length-1).sourceurl.substring(0,6)== "dvb://")
								runDTT -= 1;
						}
						break;
					case top.Video.videoRecorder.CANCELED_LIST:
						if(top.Video.recordingIPchannel)
								if(top.Video.getUrlRecordType(top.Video.videoRecorder.cancelled.item(top.Video.videoRecorder.cancelled.length-1).sourceurl)=="1")
									top.Video.recordingIPchannel=false;
						//top.warning(top._GLOC("dvr.cancelled1")+" '"+top.Video.videoRecorder.cancelled.item(top.Video.videoRecorder.cancelled.length-1).label.substr(1)+"' "+top._GLOC("dvr.cancelled2"),new Array(null,top._GLOC(5,121),null,null),null,false);
						break;
				}
				break;
		}
	}

///////////
function VideoObject (obj, svideo) {
	this.videoPlayer=null;
	this.videoRecorder=null;
	this.actualUrl=null;
	this.STATE_LOADED	= 1;
	this.STATE_UNLOADED	= 2;
	this.STATE_ERROR	= 4;
	this.STATE_NOCHANNEL	= 5;
	this.STATE_PLAYING	= 6;
	this.TYPE_VIDEO	= 1;
	this.TYPE_AUDIO	= 2;
	this.STATUS_VOD_PAUSE	= 2;
	this.STATUS_VOD_STOP	= 4;
	this.STATUS_VOD_PLAY	= 1;
	this.STATUS_VOD_FWD	= 5;
	this.STATUS_VOD_REW	= 6;
	this.FAST		= 16;
	this.SLOW		= 8;
	this.NORMAL = 0;
	this.velocidad = this.NORMAL;
	this.actualAudioStream=0;
	this.state=1;
	this.recordingIPchannel=false;
	this.freeDVRspace=ialEnv.createInformationObject("var.hdd.dvr.free");
	try{
		//this.allowed_records=parseInt(ialEnv.createInformationObject("const.hdd.record_sessions").getValue());
		this.allowed_records=1;
		if(ialEnv.createInformationObject("const.capabilities.hdd").getValue()!="true")
			this.allowed_records=0;
	}catch(e){
		this.allowed_records=0;
	}
	this.AVC_SD_bandwidth=2.3/8;
	this.MPEG2_SD_bandwidth=3.5/8;
	this.server=svideo;
	this.colorKey="003333";
	this.offset=new Array(26,0,12,4);
	this.mode=null;
	this.isTransparent=false;
	this.setAudio=function() { Debug("Video.setAudio()"); }
	this.setVideo=function() { Debug("Video.setVideo()"); }

	this.epgInit=function() {
		if (this.isTransparent) return;
		ialEnv.browserWindow.setTransparency(225);
		this.isTransparent=true;
	}
	this.epgDeInit=function() {
		if (!this.isTransparent) return;
		ialEnv.browserWindow.setTransparency(255);
		this.isTransparent=false;
	}
	this.checkChangeChannel=function(tipo,url){
		switch (tipo) {
			case "1": case 1:
			case "2": case 2: 
			case "3": case 3:
				if(this.recordingIPchannel){
					if(this.videoRecorder.running.length>0){
						if(this.videoRecorder.running.item(0).sourceurl.indexOf(url)<0){
							return false;
						}
					}else{
						if(this.videoRecorder.scheduled.item(0).sourceurl.indexOf(url)<0){
							return false;
						}
					}
				}
			case "4": case 4:
			case "5": case 5:
				return true;
		}
	}
	this.setChannel=function(url,tipo,shifttv) {
		var shifttv_param="none";
		this.stop();
		this.actualUrl=url;
		top.setVideoConfig (-1,-1);
		switch (tipo) {
			case "1": case 1:
			case "3": case 3:
				if (shifttv) shifttv_param=shifttv;
				else shifttv_param="auto";
				//rtsp
				//url="igmp://"+url;
				url="rtsp://"+url+"/MediaExtender";
				top.Video.event_Failed=function() {
					alert ("Se ha producido un error al visualizar el contenido. Por favor, reintente la operación en unos instantes.");
				}
				top.Video.load_vod(url,1, 1, "","");
				alert(url);
				top.Video.play_vod();
				break;
			case "2": case 2: 
				shifttv_param="none";
				url="igmp://"+url;
				break;
			case "4": case 4:
				if (shifttv) shifttv_param=shifttv;
				else shifttv_param="auto";
				url="dvb://"+url;
				break;
			case "5": case 5:
				shifttv_param="none";
				url="dvb://"+url;
				break;
		}
		/* rtsp
		if(this.allowed_records<1 || this.mode!="FULL") shifttv_param="none";
		try{
			this.videoPlayer.setParameter ("shifttv", shifttv_param);	
		}catch(e){}
		try{
			suceso=this.videoPlayer.open (url,null);
		}catch(e){ alert(e);}*/
	}
	this.stop=function() { try { this.videoPlayer.close(); this.velocidad = this.NORMAL;} catch (e) {} this.actualUrl=null;}
	this.runTeletext=function() { 
		try
       		{
              		var si=this.videoPlayer.getStreamInfo();
              		if(si.teletextComponents.length>0)
              		{
                   		var sc=si.teletextComponents.item(0);
                   		this.videoPlayer.setActiveTeletextComponent (sc);
              		}
       		} 
       		catch (e) {}
	}
	this.setAudio=function(estado) { this.lastError = this.media.setOption("audio content",estado); }
	this.setVideo=function(estado) { this.lastError = this.media.setOption("video content",estado); }

	this.setAudioType=function (left,right) {
		if (left&&right) try {
			this.videoPlayer.setParameter ("audiochannels", "both");
		} catch (e) {} else try {
			if (left) this.videoPlayer.setParameter ("audiochannels", "left"); else if (right) this.videoPlayer.setParameter ("audiochannels", "right");
		} catch (e) {}
	}
	this.setAudioStream=function (i) {
		try {
			var si=this.videoPlayer.getStreamInfo();
			var ac=si.audioComponents.item(i-1);
			this.videoPlayer.setActiveAudioComponent (ac);
			this.actualAudioStream=i;
			top._startAudio=i;
		} catch (e) {}
	}
	this.setSubtitles=function (i) {
		try {
			if(i>=0){
				var si=this.videoPlayer.getStreamInfo();
				var sc=si.subtitleComponents.item(i);
				this.videoPlayer.setActiveSubtitleComponent (sc);
			}else{
				this.videoPlayer.setActiveSubtitleComponent (-1);
			}
		} catch (e) {}
	}
	this.load_vod=function(url,tiempo_inicio, naudio, kenc, macro) {
		this.stop();
		if (kenc.length>0) try { this.videoPlayer.setParameter ("kenc", kenc); } catch (e) {}
		if (macro.length>0) try { this.videoPlayer.setParameter ("macrovision", macro); } catch (e) {}
		top.__tiempoinicial=tiempo_inicio*1000;
		top.__audioinicial=naudio;
		top.setVideoConfig (top.__tiempoinicial, top.__audioinicial);
		var params="server="+(this.server==1?"ncube":"concurrent");
		if(this.allowed_records>0) params+="&shifttv=none";
		this.videoPlayer.open (url, params);
		this.actualUrl=url;
	}
	this.stop_vod=this.stop;
	this.unload_vod=this.stop;
	this.rewind_vod=function()  {
		var actPace=0;
		try { actPace=this.videoPlayer.getPace(); } catch (e) {}
		if (actPace==-8000) actPace=-16000; else actPace=-8000;
		if( actPace==-8000) this.velocidad = this.SLOW; else this.velocidad = this.FAST;
		try { this.videoPlayer.play(actPace,-1,-1); } catch (e) {}
		this.state=this.STATUS_VOD_REW;
	}
	this.forward_vod=function() {
		var actPace=0;
		try { actPace=this.videoPlayer.getPace(); } catch (e) {}
		if (actPace==8000) actPace=16000; else actPace=8000;
 	  if(actPace==8000) this.velocidad =this.SLOW; else this.velocidad=this.FAST;
		try { this.videoPlayer.play(actPace,-1,-1); } catch (e) {}
		this.state=this.STATUS_VOD_FWD;
	}
	this.play_vod=function () 	{
		try { this.videoPlayer.play(1000,-1,-1); } catch (e) {}
		this.setAudioStream(this.actualAudioStream);
		this.velocidad=this.NORMAL;
		this.state=this.STATUS_VOD_PLAY;
	}
	this.pause_vod=function()   {
		this.state=this.STATUS_VOD_PLAY;
		this.velocidad=this.NORMAL;
		try { this.videoPlayer.pause();} catch (e) {}
	}
	this.getTime_vod=function() { try { return this.videoPlayer.getPosition()/1000; } catch (e) { return 0; } }
	this.goTimeOnPlay=function(t) {	try { this.videoPlayer.play (1000,t*1000,-1); this.velocidad=this.NORMAL;} catch (e) {} }
	this.configPip=function(x,y,w,h) {
//		if (this.mode!="WIN") try {
			if(this.shifttvState()!="none") this.videoPlayer.setParameter("shifttv","none");
			this.videoPlayer.window.setFullVideoSource();
			this.videoPlayer.window.setPosition (x+this.offset[0],y+this.offset[1],w+this.offset[2],h+this.offset[3]);
			this.mode="WIN";
//		} catch (e) {}
	}
	this.configFull=function() {
		if (this.mode!="FULL"){
			try{
				var typeActualChannel=this.getActualChannelType();
				if((this.allowed_records>0)&&(this.shifttvState()!="auto") && (typeActualChannel=="1" || typeActualChannel=="4")) this.videoPlayer.setParameter("shifttv","auto");
			}catch(e){}
			try {
      	this.videoPlayer.window.setFullVideoSource();
        this.videoPlayer.window.setFullScreen();
			//this.videoPlayer.window.setFullScreen();
				this.mode="FULL";
			} catch (e) {}
		}
	}
	this.setVideoVisibility=function(boo) {}
	
	this.getActualUrl=function() {
		return this.actualUrl;
	}
		
/*		// Antigua Funcion para devolver URL actual
		var uri=null;
		try { uri=""+this.videoPlayer.getStreamInfo().uri; } catch (e) {}
		if (uri.indexOf ("igmp://")==0) uri=uri.substring(7);
		return uri;
*/

	this.getUrlRecordType=function(url) {
		if(url.indexOf("igmp")>=0) return "1";
		if(url.indexOf("dvb")>=0) return "4";
		return "0";
	}
	
	this.getActualChannelType=function(){
		if(this.videoPlayer.getStreamInfo().uri.indexOf("igmp")>=0){
			if(this.videoPlayer.getStreamInfo().videoComponents.length>0) return "1"
			else return "2";
		}
		if(this.videoPlayer.getStreamInfo().uri.indexOf("dvb")>=0){
			if(this.videoPlayer.getStreamInfo().videoComponents.length>0) return "4"
			else return "5";
		}
		return "0";
	}
	
	this.checkRecordConflict=function(start_time,duration){
		var sched_start;
		for(i=0;i<this.videoRecorder.scheduled.length;i++){
			sched_start=new Date("20"+this.videoRecorder.scheduled.item(i).starttime.substr(0,2),""+(parseInt(this.videoRecorder.scheduled.item(i).starttime.substr(2,2))-1),this.videoRecorder.scheduled.item(i).starttime.substr(4,2),this.videoRecorder.scheduled.item(i).starttime.substr(7,2),this.videoRecorder.scheduled.item(i).starttime.substr(9,2),this.videoRecorder.scheduled.item(i).starttime.substr(11,2)).getTime();
			if(start_time<sched_start){
				if(start_time+1000*duration>sched_start) return (i+this.allowed_records);
			}else if(start_time<sched_start+1000*this.videoRecorder.scheduled.item(i).length){
				return (i+this.allowed_records);
			}
		}
		for(i=0;i<this.videoRecorder.running.length;i++){
			sched_start=new Date("20"+this.videoRecorder.running.item(i).starttime.substr(0,2),""+(parseInt(this.videoRecorder.running.item(i).starttime.substr(2,2))-1),this.videoRecorder.running.item(i).starttime.substr(4,2),this.videoRecorder.running.item(i).starttime.substr(7,2),this.videoRecorder.running.item(i).starttime.substr(9,2),this.videoRecorder.running.item(i).starttime.substr(11,2)).getTime();
			if(start_time<sched_start){
				if(start_time+1000*duration>sched_start) return i;
			}else if(start_time<sched_start+1000*this.videoRecorder.running.item(i).length){
				return i;
			}
		}
		return -1;
	}
	
	this.addInstantRecord=function(channel,channel_name,channel_type,parental_control){
		if(channel_type!="1" && channel_type!="4" && channel_type!=1 && channel_type!=4) return -2;
		var now=new Date();
		var recordName=now.getFullYear()+"."+((now.getMonth()+1)<10?"0":"")+(now.getMonth()+1)+"."+(now.getDate()<10?"0":"")+now.getDate()+"."+(now.getHours()<10?"0":"")+now.getHours()+"."+(now.getMinutes()<10?"0":"")+now.getMinutes()+"."+channel;
		var channel_number=""+channel;
		if(channel<100) channel_number="0"+channel_number;
		if(channel<10) channel_number="0"+channel_number;
		var label=(parental_control?"1":"0")+channel_number+" "+channel_name+" "+(now.getDate()<10?"0":"")+now.getDate()+"/"+((now.getMonth()+1)<10?"0":"")+(now.getMonth()+1)+"/"+now.getFullYear().toString().substr(2,2)+" "+(now.getHours()<10?"0":"")+now.getHours()+":"+(now.getMinutes()<10?"0":"")+now.getMinutes();
		var start=(new Date()).getTime()+100;
		var duration=9000;
		if(this.checkRecordConflict(start,duration)>=0) return -3;
		var bandwidth=((channel_type=="1" || channel_type==1)?this.AVC_SD_bandwidth:this.MPEG2_SD_bandwidth);
		var freeTime=this.getFreeSpace()/bandwidth;
		var partialRecord=false;
		if(freeTime<duration){
			if(freeTime<=49) return -4;
			duration=freeTime-49;
			partialRecord=true;
		}
		try{
			this.videoRecorder.addRecordByTime("",recordName,label,this.videoPlayer.getStreamInfo().uri,start/1000,duration);
		}catch(e){
			return -1;
		}
		if(channel_type=="1" || channel_type==1){
			if(this.recordingIPchannel){
				//We can't be in an IP channel if we are recording another IP channel
			}else{
				this.recordingIPchannel=true;
			}
		}
		if(this.checkDVRspace()>=0 || partialRecord) return 1;
		return 0;
	}
	
	this.addTimeInstantRecord=function(){
		try{
			var ind=0;
			if(this.videoRecorder.running.length>1)
				if(this.videoPlayer.getStreamInfo().uri==this.videoRecorder.running.item(1).sourceurl)
					ind=1;
			var new_length=this.videoRecorder.running.item(ind).length+1800;
			var run_start=new Date("20"+this.videoRecorder.running.item(ind).starttime.substr(0,2),""+(parseInt(this.videoRecorder.running.item(ind).starttime.substr(2,2))-1),this.videoRecorder.running.item(ind).starttime.substr(4,2),this.videoRecorder.running.item(ind).starttime.substr(7,2),this.videoRecorder.running.item(ind).starttime.substr(9,2),this.videoRecorder.running.item(ind).starttime.substr(11,2)).getTime();
			if(this.checkRecordConflict(run_start,new_length)>this.allowed_records-1) return -3;
			var channel_type=this.getUrlRecordType(this.videoRecorder.running.item(0).sourceurl);
			var bandwidth=((channel_type=="1" || channel_type==1)?this.AVC_SD_bandwidth:this.MPEG2_SD_bandwidth);
			var freeTime=this.getFreeSpace()/bandwidth;
			var partialRecord=false;
			if(freeTime<1800){
				partialRecord=true;
				if(freeTime<=49) return 1;
				else new_length=this.videoRecorder.running.item(ind).length+freeTime-49;
			}
			this.videoRecorder.running.item(ind).changeDuration(new_length);
		}catch(e){
			return -1;
		}
		if(this.checkDVRspace()>=0 || partialRecord) return 1;
		return 0;
	}
	
	this.stopActualRecord=function(){
		try{
			var ind=0;
			if(this.videoRecorder.running.length>1)
				if(this.videoPlayer.getStreamInfo().uri==this.videoRecorder.running.item(1).sourceurl)
					ind=1;
			if(this.recordingIPchannel)
				if(this.getUrlRecordType(this.videoRecorder.running.item(ind).sourceurl)=="1")
					this.recordingIPchannel=false;
			this.videoRecorder.running.item(ind).changeDuration(this.videoRecorder.running.item(ind).getCurrentLength());
		}catch(e){
			return false;
		}
		return true;
	}
	
	this.delActualRecord=function(){
		try{
			var ind=0;
			if(this.videoRecorder.running.length>1)
				if(this.videoPlayer.getStreamInfo().uri==this.videoRecorder.running.item(1).sourceurl)
					ind=1;
			if(this.recordingIPchannel)
				if(this.getUrlRecordType(this.videoRecorder.running.item(ind).sourceurl)=="1")
					this.recordingIPchannel=false;
			this.videoRecorder.running.item(ind).destroy();
		}catch(e){
			return false;
		}
		return true;
	}
	
	this.addRecord=function(url,start_time,duration,channel,channel_name,channel_type,program_name,parental_control){
		switch(channel_type){
			case "1": case 1: url="igmp://"+url; break;
			case "4": case 4: url="dvb://"+url; break;
		}
		if(this.checkRecordConflict(start_time,duration)>=0) return -3;
		var start=new Date(start_time);
		var recordName=start.getFullYear()+"."+((start.getMonth()+1)<10?"0":"")+(start.getMonth()+1)+"."+(start.getDate()<10?"0":"")+start.getDate()+"."+(start.getHours()<10?"0":"")+start.getHours()+"."+(start.getMinutes()<10?"0":"")+start.getMinutes()+"."+channel;
		var channel_number=""+channel;
		if(channel<100) channel_number="0"+channel_number;
		if(channel<10) channel_number="0"+channel_number;
		var label="";
		if(program_name.length>0){
			label=(parental_control?"1":"0")+channel_number+" "+channel_name+" "+program_name;
		}else{
			label=(parental_control?"1":"0")+channel_number+" "+channel_name+" "+(start.getDate()<10?"0":"")+start.getDate()+"/"+((start.getMonth()+1)<10?"0":"")+(start.getMonth()+1)+"/"+start.getFullYear().toString().substr(2,2)+" "+(start.getHours()<10?"0":"")+start.getHours()+":"+(start.getMinutes()<10?"0":"")+start.getMinutes();
		}
		var start_secs=start.getTime()/1000;
		try{
			this.videoRecorder.addRecordByTime("",recordName,label,url,start_secs,duration);
		}catch(e){
			return -1;
		}
		if(this.checkDVRspace()>=0) return 1;
		return 0;
	}
	
	this.checkDVRspace=function(){
		var bandwidth=0;
		var duration=0;
		var freeSpace=parseInt(this.freeDVRspace.getValue());
		for(i=0;i<this.videoRecorder.running.length;i++){
			switch(this.getUrlRecordType(this.videoRecorder.running.item(i).sourceurl)){
				case "1": bandwidth=this.AVC_SD_bandwidth; break;
				case "4": bandwidth=this.MPEG2_SD_bandwidth; break;
			}
			duration+=((this.videoRecorder.running.item(i).length-this.videoRecorder.running.item(i).getCurrentLength())*bandwidth);
		}
		for(i=0;i<this.videoRecorder.scheduled.length;i++){
			switch(this.getUrlRecordType(this.videoRecorder.scheduled.item(i).sourceurl)){
				case "1": bandwidth=this.AVC_SD_bandwidth; break;
				case "4": bandwidth=this.MPEG2_SD_bandwidth; break;
			}
			duration+=(this.videoRecorder.scheduled.item(i).length)*bandwidth;
			if(freeSpace < duration) return i;
		}
		return -1;
	}
	
	this.getFreeSpace=function(){
		var bandwidth=0;
		var duration=0;
		var freeSpace=parseInt(this.freeDVRspace.getValue());
		for(i=0;i<this.videoRecorder.running.length;i++){
			switch(this.getUrlRecordType(this.videoRecorder.running.item(i).sourceurl)){
				case "1": bandwidth=this.AVC_SD_bandwidth; break;
				case "4": bandwidth=this.MPEG2_SD_bandwidth; break;
			}
			duration+=((this.videoRecorder.running.item(i).length-this.videoRecorder.running.item(i).getCurrentLength())*bandwidth);
		}
		for(i=0;i<this.videoRecorder.scheduled.length;i++){
			switch(this.getUrlRecordType(this.videoRecorder.scheduled.item(i).sourceurl)){
				case "1": bandwidth=this.AVC_SD_bandwidth; break;
				case "4": bandwidth=this.MPEG2_SD_bandwidth; break;
			}
			duration+=(this.videoRecorder.scheduled.item(i).length)*bandwidth;
		}
		return (freeSpace-duration);
	}
	
	this.shifttvState=function(){
		var shifttv="";
		if(this.allowed_records<1) return "none";
		try{
			shifttv=""+this.videoPlayer.getParameter("shifttv");
		}catch(e){
			shifttv="none";
		}
		return shifttv;
	}

	this.getState=function() {
		var pace=-1;
		try { pace=this.videoPlayer.getPace(); } catch (e) {}
		if (pace==-1) return this.STATUS_VOD_STOP;
		if (pace==1000) return this.STATUS_VOD_PLAY;
		if (pace>2000) return this.STATUS_VOD_FWD;
		if (pace<-2000) return this.STATUS_VOD_REW;
		if (pace==0) return this.STATUS_VOD_PAUSE;
	}
	this.event_Edge=function() {}
	this.deInit=function() {
			ialEnv.browserWindow.setPosition (30,0,768,576);		
			ialEnv.system.disableColorKeying();
	}
	this.initObject=function() {
		try {

			this.videoPlayer=ialEnv.createMediaPlayer();
			this.videoPlayer.addEventListener (this.videoPlayer.ON_STATE_CHANGED, top.videoListener);
			this.videoPlayer.addEventListener (this.videoPlayer.ON_STREAM_CHANGED, top.streamListener);
			try{
				this.videoRecorder=tmpEnv.recorder;
				this.videoRecorder.addEventListener (this.videoRecorder.ON_STATE_CHANGED, top.recordListener);
			}catch(ex){}
			this.reinit();

		} catch (e) {
			e.description="Sistema/Video: "+e.description;
			throw e;
		}
	}
	this.reinit=function() {
		try {
			//ialEnv.browserWindow.setPosition (0,0,768,576);
			ialEnv.system.enableColorKeying();
			this.videoPlayer.window.show();
			this.videoPlayer.window.setColorKey (parseInt ("0x"+this.colorKey,16));
			this.actualAudioStream=0;
			try{
				for(i=0;i<this.videoRecorder.running.length;i++){
					if(this.getUrlRecordType(this.videoRecorder.running.item(i).sourceurl)=="1"){
						this.recordingIPchannel=true;
						break;
					}
				}
			}catch(ex){}
			this.mode=null;
			this.configFull();
		} catch (e) {
			
			throw ("Video.reinit error: "+e.description);	
		}
	}
	this.reinitAll=function() {
		try {
			//alert ("se va a morir");
			this.videoPlayer.destroy();
			this.initObject();
		} catch (e) {
			
			throw ("Video.reinit error: "+e.description);	
		}
	}

	this.initObject();
	return this;
}

//////////////////////////////////////////////////////////////////////////////////////////
// Internet Functions

var MultiBrowser=function() {
	this.BrowserInternet=null;
	this.BrowserNtf=null;
	this.filled=false;
	this.ntfInited = false;
	this.ntfOpened = false;
	this.activeBrw = 0;
	
	this.initBrowsers=function () {
		ialEnv.browserWindow.setDepth(1);
		if (this.BrowserInternet==null) try {
			this.BrowserInternet=ialEnv.createBrowser();
			this.BrowserInternet.window.setFullScreen();
			this.BrowserInternet.window.setPosition (30,10,660,576);
			this.BrowserInternet.window.setDepth(2);
			this.BrowserInternet.window.show();
		} catch (e) {
			e.description="Multibrowser Internet: "+e.description;
			throw e;
		}
		if (this.BrowserNtf==null) try {
			this.BrowserNtf=ialEnv.createBrowser();
			this.BrowserNtf.window.setPosition (30,876,660,150);
			this.BrowserNtf.window.setDepth(0);
			this.BrowserNtf.window.show();
			//Carga de la aplicacion notificador
			this.BrowserNtf.load(document.URL.substring(0,document.URL.indexOf("/",7))+"/app_pace2/notificador/notificador.html");
			this.ntfInited = true;
		} catch (e) {
			e.description="Multibrowser Notificador: "+e.description;
			throw e;
		}
	}
	this.launchUrlInChild=function (url,ours) {
		if (arguments.length<2) ours=false;
		if ((""+url).toLowerCase().indexOf("http://")<0) url="http://"+url;
		if (this.BrowserInternet!=null){
			try {//1
				if(!ours){
					try{ialEnv.browserWindow.setFocusMode(1);}catch (ex) {}		// Habilitar entrega automática de foco en ADB
					ialEnv.system.disableColorKeying();
					this.showInternetBrowser();
				}
				if ((this.BrowserInternet.getCurrentUri() == "") && ((url == null) || (url == ""))) this.goHome();
				else {this.gotoUrl(url);}
			} catch (e) {alert ("internet navigation not possible with this hardware");} 
		}else alert ("internet navigation not possible with this hardware");

	}
	
	
	this.gotoUrl=function (url) {
		if ((""+url).length>3) {
			this.BrowserInternet.load(url);
			this.filled=true;
		}
	}
	this.goBack=function (num) {	
		try{
			if(!num) num=0;
			var h=this.BrowserInternet.backList;
			if(h.length==0) return;
			if(num>h.length-1) num=h.length-1;
			var vconf=h.item(num).indexOf("vconf");
			var blank=h.item(num).indexOf("blank.html");
			if ((vconf!=-1) || (blank!=-1)) {try{this.BrowserInternet.clearHistory(); h=this.BrowserInternet.backList;return;}catch(e){}}		
			if (h.item(num)!=null) this.BrowserInternet.loadFromHistory (h.item(num));
		} catch(e){}
	}
	this.goForward=function (num) {
		try{
			if(!num) num=0;
			var h=this.BrowserInternet.forwardList;
			if(h.length==0) return;
			if(num>h.length-1) num=h.length-1;
			if (h.item(num)!=null) this.BrowserInternet.loadFromHistory (h.item(num));
		} catch(e){}
	}
	this.goHome=function() {
		var home = null;
		try {top.cliente.url
			var obj = ialEnv.createInformationObject ("cfg.browser.home.internet");
			home = obj.getValue();
		} catch (ex) {home="http://www.terra.es";}
		if ((top.cliente.url == null) || (top.cliente.url == "")) this.gotoUrl (home);
		else this.gotoUrl (top.cliente.url);
	}
	this.reload=function() {
		this.BrowserInternet.reload ();
	}
	this.getUrl=function() {
		return this.BrowserInternet.getCurrentUri();
	}
	this.getTitle=function() {
		return this.BrowserInternet.document.title;
	}
	this.isLoading=function() {
		return this.BrowserInternet.isLoading();
	}
	this.hideChild=function(borrar) {
		try {

			try {this.BrowserInternet.stop(); } catch (e) {}
			if (!borrar) this.blankChild();
			this.BrowserInternet.window.setDepth(1);
			this.BrowserNtf.load("");
			ialEnv.browserWindow.setDepth(0);
			ialEnv.browserWindow.activate();
			ialEnv.system.enableColorKeying();
			top.Video.videoPlayer.window.setColorKey (parseInt ("0x"+top.Video.colorKey,16));
			try{ialEnv.browserWindow.setFocusMode(0);}catch (ex) {}				// Deshabilitar entrega automática de foco en ADB
		} catch (e){
			//alert ("hidechild fails");
		}
	}
	this.blankChild=function() {
		if (this.filled) {
			try{
				try {this.BrowserInternet.stop(); } catch (e) {}
//				s=top.ToiUtils.getToken("const._browser.home.local");
//				if(s!="")s=s.substring(0,s.lastIndexOf("/"));
//				s+="/blank.html";
//				this.BrowserInternet.load(s);
				this.BrowserInternet.load(top.BLANKPAGE);
			}catch(e){} 
			this.filled=false;
		}
	}
	this.showNtfBrowser=function() {this.ntfOpened=true;}
	
	this.hideNtfBrowser=function(GS) {
		if(!this.ntfOpened) return;
		if(arguments.length<1) GS=false;
		if(GS) ToiUtils.sendMessage(top.ToiUtils.MSG_HIDE_NOTIF_GS,0);
		if(this.activeBrw==1) this.BrowserInternet.window.activate();
		else ialEnv.browserWindow.activate();
		this.ntfOpened=false;


	}
	
	this.showInternetBrowser=function() {
		playPortalAudio(true,false);
		ialEnv.browserWindow.setDepth(2);
		this.BrowserInternet.window.setDepth(1);
		this.activeBrw=1;
		this.BrowserInternet.window.activate();
	}
	
	this.hideInternetBrowser=function(borrar) {
		playPortalAudio(false,true);
		try {this.BrowserInternet.stop(); } catch (e) {}
		if (!borrar) this.blankChild();		
		ialEnv.browserWindow.setDepth(1);
		this.BrowserInternet.window.setDepth(2);
		ialEnv.system.enableColorKeying();
		try{ialEnv.browserWindow.setFocusMode(0);}catch (ex) {}// Deshabilitar entrega automática de foco en ADB
		this.activeBrw=0;
		if(!this.BrowserNtf.window.isActive())ialEnv.browserWindow.activate();
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
// TOI misc utils

var ToiUtils=new Object();
ToiUtils.recv = null;		// Cola de Mensajes de Entrada
ToiUtils.enviar = null;		// Cola de Mensajes de Salida

ToiUtils.MSG_KEYPRESS=100;
ToiUtils.MSG_BROWSER_BACK=101;
ToiUtils.MSG_BROWSER_FORWARD=102;
ToiUtils.MSG_BROWSER_HOME=103;
ToiUtils.MSG_BROWSER_RELOAD=104;
ToiUtils.MSG_BROWSER_FAVORITOS=105;
ToiUtils.MSG_BROWSER_FAVORITOS_ADD=106;
ToiUtils.MSG_BROWSER_GO_URL=107;

ToiUtils.MSG_BROWSER_APPLOADED=108;
ToiUtils.MSG_BROWSER_UNLOADAPP=109;

ToiUtils.MSG_DISABLE_NOTHING=120;
ToiUtils.MSG_DISABLE_BACK=121;
ToiUtils.MSG_DISABLE_FORWARD=122;
ToiUtils.MSG_DISABLE_BOTH=123;

ToiUtils.MSG_3RDPARTY_APP=200;

ToiUtils.MSG_SHOW_NOTIF=400;
ToiUtils.MSG_HIDE_NOTIF=401;
ToiUtils.MSG_SET_NOTIF_SERVICE=402;
ToiUtils.MSG_LOAD_THIRDPARTY_APP=403;
ToiUtils.MSG_HIDE_NOTIF_GS=404;
ToiUtils.MSG_NOTIF_LOADED=405;

ToiUtils.TOKEN_TIMEZONE="cfg.locale.timezone";

ToiUtils.sendMessage=function (tipo, codigo, str)  {
	var mensaje=null;
	try {
		mensaje = tipo + "|" + codigo;
		if (str) mensaje += "|" + str;
		//Sustituimos la siguiente linea por otra para evitar que no se ejecute la excepcion en el caso de un código 1001		
		//ToiUtils.enviar.setValue (mensaje, ToiUtils.enviar.STORAGE_VOLATILE);
		try{ToiUtils.enviar.setValue (mensaje, ToiUtils.enviar.STORAGE_VOLATILE);}catch(e){top.debug("VideoObject->sendMessage error:"+e);try{ToiUtils.enviar.setValue (mensaje, ToiUtils.enviar.STORAGE_VOLATILE);}catch(e){top.debug("VideoObject->sendMessage error2:"+e)}}
	} catch (ex) {return false; }
	return true;
}

ToiUtils.sendMessage3rdparty=function (tipo, codigo, str)  {
	var mensaje=null;
	try {
		mensaje = tipo + "|" + codigo;
		if (str) mensaje += "|" + str;
		//Sustituimos la siguiente linea por otra para evitar que no se ejecute la excepcion en el caso de un código 1001		
		//ToiUtils.enviar3rdparty.setValue (mensaje, ToiUtils.enviar3rdparty.STORAGE_VOLATILE);
		try{ToiUtils.enviar3rdparty.setValue (mensaje, ToiUtils.enviar3rdparty.STORAGE_VOLATILE);}catch(e){top.debug("VideoObject->enviar3rdparty error:"+e);try{ToiUtils.enviar3rdparty.setValue (mensaje, ToiUtils.enviar3rdparty.STORAGE_VOLATILE);}catch(e){top.debug("VideoObject->enviar3rdparty error2:"+e)}}
	} catch (ex) {return false; }
	return true;
}

ToiUtils.initMessages=function() {
	try {
		ToiUtils.recv = ialEnv.createInformationObject("_tmp.notif2");
		ToiUtils.enviar = ialEnv.createInformationObject("_tmp.notif1");
		ToiUtils.recv3rdparty = ialEnv.createInformationObject("_tmp.3rdparty2");
		ToiUtils.enviar3rdparty = ialEnv.createInformationObject("_tmp.3rdparty1");
		try {ToiUtils.recv.addEventListener (ToiUtils.recv.ON_OBJECT_CHANGED, ToiUtils.messageListener);} catch (ex) {}    //ON_OBJECT_CHANGED
		try {ToiUtils.recv3rdparty.addEventListener (ToiUtils.recv3rdparty.ON_OBJECT_CHANGED, ToiUtils.messageListener3rdparty);} catch (ex) {}    //ON_OBJECT_CHANGED
	} catch (e) {
		//alert(e);
		e.description="Sistema/MsgQueue: "+e.description;
		throw e;
	}
}

//Listener mensajes notificador
ToiUtils.messageListener=function(ev) {


//	if ((top.sysStatus!=top.ST_INTERNET)) return;
	
	
	var tipo=null, code=null, str=null;

	try {
		var msg = ToiUtils.recv.getValue();
		var mensaje = msg.split("|");
		tipo = parseInt (mensaje[0]);
		code = parseInt (mensaje[1]);
		try {str = mensaje[2];} catch (ex) {str="";}
	} catch (e) {}

	try {
		switch (tipo) {
			case ToiUtils.MSG_BROWSER_BACK:

				top.multiBrowser.goBack();
				break;
			case ToiUtils.MSG_BROWSER_FORWARD:

				top.multiBrowser.goForward();
				break;
			case ToiUtils.MSG_BROWSER_HOME:

				top.multiBrowser.goHome();
				break;
			case ToiUtils.MSG_BROWSER_GO_URL:
				if (str != "") {

					top.multiBrowser.gotoUrl (str);
				}
				break;
			case ToiUtils.MSG_BROWSER_FAVORITOS:
				top.runList ("Internet>Favoritos","internet/data-favoritos.asp");
				top.setTimeout("top.multiBrowser.hideInternetBrowser(true);",3000);
				break;
			case ToiUtils.MSG_BROWSER_FAVORITOS_ADD:
				var url = top.multiBrowser.getUrl();
				if ((url.length > 128) || (url == null)) {
					alert ("Favorito NO añadido\nDirección demasiado larga"); break;
				}
				nombre=str;
				if (nombre != "") {
					if (nombre.length > 40) break;
					var bookmark = nombre+"|"+url;
					ToiUtils.saveBookmark (bookmark);
				}
				break;
			case ToiUtils.MSG_BROWSER_RELOAD:
				top.multiBrowser.reload();
				break;
			case ToiUtils.MSG_SHOW_NOTIF:
				if(!top.multiBrowser.ntfOpened) top.multiBrowser.showNtfBrowser();
				break;
			case ToiUtils.MSG_HIDE_NOTIF:
				top.multiBrowser.hideNtfBrowser();
				break;
			case ToiUtils.MSG_LOAD_THIRDPARTY_APP:
				//de momento solo carga la videoconferencia
				//top.Video.stop();
				top.multiBrowser.hideNtfBrowser(true);
				if (top.rootTitle==null) top.rootTitle=top._GLOC("notif.tit");
				top.loadThirdPartyApp(str,"");
				break;		
			case top.ToiUtils.MSG_NOTIF_LOADED:
				top.notifModules=str;
				top.notifLoaded=true;
				break;
			default:
				top.msglistenersegundos(tipo,str);						
		}	
	} catch (e) {}
}


//Listener mensajes brower internet/3rdparty
ToiUtils.messageListener3rdparty=function(ev) {
	var tipo=null, code=null, str=null, videostop=false;
	try {
		var msg = ToiUtils.recv3rdparty.getValue();
		var mensaje = msg.split("|");
		tipo = parseInt (mensaje[0]);
		code = parseInt (mensaje[1]);
		try {str = mensaje[2];} catch (ex) {str="";}
	} catch (e) {}

	try {
		switch (tipo) {
			case ToiUtils.MSG_BROWSER_APPLOADED:
				top.thirdPartyAppLoaded(); break;
			case ToiUtils.MSG_BROWSER_UNLOADAPP:
				switch (code){
					case 1: try{top.goHome();break;}catch(e){}
					case 2: try{top.run_promoEsp();videostop=true;break;}catch(e){}

					default: Video.stop();
				}
				top.unloadThirdPartyApp(videostop); 
 
				
		}
	} catch (e) {}
}


////////////////////// Favoritos /////////////////////////////////

ToiUtils.getBookmarkNum = function(i) {
	var names_str, urls_str;
	var names = null; var urls = null;

	try {																		// Lectura de Tokens
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		names_str = obj_names.getValue();
		var obj_urls = ialEnv.createInformationObject ("_env.trusted.1");
		urls_str = obj_urls.getValue();
	} catch (ex) {return null;}

	try {names = names_str.split("|"); urls = urls_str.split("|");}
	catch (ex) {names = new Array(); urls = new Array();}

	// Devuelve el bookmark en formato un array (nombre, url)
	if ((i >= 0) && (i < names.length))	return new Array (names[i].substring(0,40),urls[i]);
	else return null;
}

ToiUtils.getBookmarkCount = function(i) {
	var names_str;
	var names = null;

	try {																		// Lectura de Tokens
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		names_str = parseInt(obj_names.getValue());
	} catch (ex) {return 0;}
	names = names_str.split("|");

	// Devuelve el número de bookmarks almacenados.
	return names.length;
}

ToiUtils.saveBookmark = function (value) {
	var names_str, urls_str;
	var names = null; var urls = null;
	
	try {																		// Lectura de Tokens
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		names_str = obj_names.getValue();
		var obj_urls = ialEnv.createInformationObject ("_env.trusted.1");
		urls_str = obj_urls.getValue();
	} catch (ex) {urls_str = ""; names_str = "";}
	
	try {names = names_str.split("|"); urls = urls_str.split("|");}
	catch (ex) {names = new Array(); urls = new Array();}

	// Comprobar que haya tantos nombres como urls. Si no se quita del mayor hasta que se igualen.
	while (names.length != urls.length) {
		if (names.length > urls.length) names.pop();
		else urls.pop();
		names_str = names.join ("|"); urls_str = urls.join ("|");
	}

	var new_bookmark = value.split ("|");
	// Comprueba que esté bien escrito el nuevo bookmark.
	if (new_bookmark.length == 2) {
		// Se añade el bookmark solo si no existe ya. Siempre se añade al final.
		if (names.length == 0) {
			names_str = new_bookmark [0];
			urls_str = new_bookmark [1];
		} else if ((names_str.toUpperCase().indexOf(new_bookmark[0].toUpperCase()) < 0) &&
			(urls_str.toUpperCase().indexOf(new_bookmark[1].toUpperCase()) < 0)) {
			names.push (new_bookmark [0]);
			urls.push (new_bookmark [1]);
			names_str = names.join ("|"); urls_str = urls.join ("|");
		}
	}

	try {																		// Escritura de Tokens
		if (names_str.charAt(0) == '|') names_str = names_str.substring (1);
		if (urls_str.charAt(0) == '|') urls_str = urls_str.substring (1);
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		obj_names.setValue (names_str, obj_names.STORAGE_PERMANENT);
		var obj_urls = ialEnv.createInformationObject ("_env.trusted.1");
		obj_urls.setValue (urls_str, obj_urls.STORAGE_PERMANENT);
	} catch (ex) {}
}

ToiUtils.delBookmarkNum = function(i) {
	var names_str, urls_str;
	var names = null; var urls = null;

	try {																		// Lectura de Tokens
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		names_str = obj_names.getValue();
		var obj_urls = ialEnv.createInformationObject ("_env.trusted.1");
		urls_str = obj_urls.getValue();
	} catch (ex) {urls_str = ""; names_str = "";}

	try {names = names_str.split("|"); urls = urls_str.split("|");}
	catch (ex) {names = new Array(); urls = new Array();}

	// Comprobar que haya tantos nombres como urls. Si no se quita del mayor hasta que se igualen.
	while (names.length != urls.length) {
		if (names.length > urls.length) names.pop();
		else urls.pop();
		names_str = names.join ("|"); urls_str = urls.join ("|");
	}

	// Si el que se quiere eliminar no existe, no se hace nada.
	if (i > names.length) return false;
	else {
		var old_name = names.splice (i,1);
		var old_url = urls.splice (i,1);
		names_str = names.join ("|"); urls_str = urls.join ("|");	
	}

	try {																		// Escritura de Tokens
		if (names_str.charAt(0) == '|') names_str = names_str.substring (1);
		if (urls_str.charAt(0) == '|') urls_str = urls_str.substring (1);
		var obj_names = ialEnv.createInformationObject ("_env.trusted.0");
		obj_names.setValue (names_str, obj_names.STORAGE_PERMANENT);
		var obj_urls = ialEnv.createInformationObject ("_env.trusted.1");
		obj_urls.setValue (urls_str, obj_urls.STORAGE_PERMANENT);
	} catch (ex) {}
}

ToiUtils.getToken=function (token_name) {
	var obj = null;
	try {
		return ialEnv.createInformationObject(token_name).getValue();
	} catch (ex) {
		return "";
	}
}
ToiUtils.setToken=function (token_name, new_value) {
	try {
		var obj = ialEnv.createInformationObject (token_name);
		obj.setValue (new_value, obj.STORAGE_PERMANENT);
		obj = null;
	} catch (ex) {}
}
