//*********************** MOVE SDK ***********************************************

//********************************************************************************

// dvr.js - Convenience class to handle DVR-like controls for a Move player object
// Copyright (c) 2007 Move Networks
// Provides a wrapper interface between the HTML controls on a page to talk to and be
// updated by a QVT player object. This class requires that you use the qvt.js version of
// CreatePlayer() to return the object that DVR uses. The developers responsibility is to
// setup a page of elements with a consistent prefix plus predefined suffixes and then
// initialize this class with the options that tell it what to handle.
//
// The following is a list of all the named parameters that are supported, what controls that
// option handles, the suffix of the element's ID, and additional comments for the feature.
//
// Option "playPause":true
// Play/Pause 		_playpause	(This requires two CSS classes to be defined, "mn_play" and "mn_pause",
//						 		which are applied to the element based on that status of the player.
//								See "playPrefix" option for additional control to class names.)
//
// Option "fwdRwd":true
// Rewind			_rew
// Fast Forward 	_fwd
//
// Option "prevNext":true			
// Previous			_prev
// Next				_next
//
// Option "scrub":true
// Slider Track		_track		(In addition, this element requires a child element that is the thumb
//								control that moves and can be dragged)
//
// Option "position":true
// Position/Length	_position
//
// Option "playState":true
// Player Status	_status
//
// Option "volume":true
// Volume			_volume
//
// Option "size":true
// Sizing			_size		(This requires two classes to be defined, "mn_sizemax" and "mn_sizemin"
//								which are applied to the element based on which mode is active)
//
// Option "live":true
// Go Live			_live
//
// Option "handleScrub":true	(Whether we should change position after user moves timeline scrubber or
//								fire a 'StopScrub' event to be handled outside this object)
//
// Option "playPrefix":"foo"	(When it is necessary to define a different class name for the playPause button,
//								setting this option makes the code look for "fooplay" and "foopause" instead)
//
// An example variable to be passed to the class on creation to enable every feature would look like this:
// var options = {"playState":true,"position":true,"bitrate":true,"playPause":true,"fwdRwd":true,"prevNext":true,
//				  "scrub":true,"volume":true,"size":true,"live":true,"handleScrub":true,"playPrefix":"foo"};

MN.Widget.DVR = MN.Class(MN.EventSource);
_mndvr = MN.Widget.DVR.prototype;

// Creates the object and sets up all the listeners and intervals for the DVR controls
// prefix - The string that precedes every element's ID e.g. "plyr1" for "plyr1_playpause"
// player - QVT wrapper object retrieved after calling CreatePlayer()
// url - Optional absolute address to QMX or QVT Move stream, pass null if you want to set later
// options - JSON object of which features to enable as described above
// autoplay - Optional true/false of whether or not to start playback immediately, default = false
// playfrom - Optional number value of seconds into clip to start playback from, requires autoplay be true
_mndvr.initialize = function(prefix, player, url, options, autoplay, playfrom)
{
	MN.EventSource.prototype.initialize.apply(this);
	this._qmp = player;
	this.player = player;
	this._slider = null;
	this._sliderSteps = 300;
	this._scrubbing = false;
	this._scrubbingvolume = false;
	this._seeking = false;
	this._scrubspeed = 0;
	this._curpos = 0;
	this._playstate = 0;
	this._bitrate = 0;
	this._options = options;
	this._prefix = prefix;
	this._url = url;
	this._posIntvl = null;
	this._seekIntvl = null;
	this._volIntvl = null;
	this._sizemax = false;
	
	if (autoplay==null) autoplay = false;
	
	if (url!=null)
	{
		if (autoplay && playfrom) this._qmp.Play(url,playfrom);
		else if (autoplay) this._qmp.Play(url);
		else this._qmp.Load(url);
	}
	
	MN.Event.Observe(this._qmp,"PlayStateChanged",this.OnPSChanged);

	if (this._options.position)
	{
		this._posIntvl = setInterval(this.UpdatePosition,1000);
	}
	MN.Event.Observe(this._qmp,"BitRateChanged",this.OnBRChanged);
	if (this._options.playPause)
	{
		MN.Event.Observe(this._qmp,"PausedChanged", this.TogglePlayPause);
		MN.Event.Observe(this._prefix + "_playpause","click",this.OnClickPlayPause);
	}
	if (this._options.fwdRwd) 
	{
		MN.Event.Observe(this._prefix + "_rew","click",this.OnClickRewind);
		MN.Event.Observe(this._prefix + "_fwd","click",this.OnClickForward);
	}
	if (this._options.scrub) 
	{
		this._slider = new MN.Widget.HSlider(this._prefix + "_track",0,this._sliderSteps);
		MN.Event.Observe(this._slider,"ValueChanged",this.OnMoveScrubber);
		MN.Event.Observe(this._slider,"SlideStart",this.OnStartScrub);
		MN.Event.Observe(this._slider,"SlideStop",this.OnStopScrub);
		this._seekIntvl = setInterval(this.UpdateScrubber,500);
	}
	if (this._options.prevNext) 
	{
		MN.Event.Observe(this._prefix + "_prev","click",this.OnClickPrevious);
		MN.Event.Observe(this._prefix + "_next","click",this.OnClickNext);
	}
	// Keep track of volume no matter what in case option is activated later
	this._volumeVal = this._qmp.Volume();
	if (this._options.volume) 
	{
		this._volume = new MN.Widget.HSlider(this._prefix + "_volume",1,100);
		MN.Event.Observe(this._volume,"ValueChanged",this.OnVolumeChange);
		MN.Event.Observe(this._volume,"SlideStart",this.OnStartVolumeScrub);
		MN.Event.Observe(this._volume,"SlideStop",this.OnStopVolumeScrub);
		this._volume.Value(this._volumeVal);
	}
	this._volIntvl = setInterval(this.UpdateVolumeScrubber,1000);
	if (this._options.size)
	{
		MN.Event.Observe(this._prefix + "_size","click",this.OnClickSize);
	}
	if (this._options.live)
	{
		MN.Event.Observe(this._prefix + "_live","click",this.OnClickLive);
	}
}
// Function attempts to unlink and clean up all of the intervals created should you want to kill
// the DVR object. 
_mndvr.Destroy = function()
{
	MN.Event.StopObserving(this._qmp,"PlayStateChanged",this.OnPSChanged);

	if (this._options.position)
	{
		clearInterval(this._posIntvl);
	}
	if (this._options.bitrate)
	{
		MN.Event.StopObserving(this._qmp,"BitRateChanged",this.OnBRChanged);
	}
	if (this._options.playPause)
	{
		MN.Event.StopObserving(this._qmp,"PausedChanged", this.TogglePlayPause);
		MN.Event.StopObserving(this._prefix + "_playpause","click",this.OnClickPlayPause);
	}
	if (this._options.fwdRwd) 
	{
		MN.Event.StopObserving(this._prefix + "_rew","click",this.OnClickRewind);
		MN.Event.StopObserving(this._prefix + "_fwd","click",this.OnClickForward);
	}
	if (this._options.scrub) 
	{
		MN.Event.StopObserving(this._slider,"ValueChanged",this.OnMoveScrubber);
		MN.Event.StopObserving(this._slider,"SlideStart",this.OnStartScrub);
		MN.Event.StopObserving(this._slider,"SlideStop",this.OnStopScrub);
		clearInterval(this._seekIntvl);
		// Currently this Destroy call invokes the function declared in this file, yet still does not completely
		// stop the mouse handlers correctly from the objects they are watching. Results are erratic until this can be fixed
		this._slider.Destroy();
		this._slider = null;
	}
	if (this._options.prevNext) 
	{
		MN.Event.StopObserving(this._prefix + "_prev","click",this.OnClickPrevious);
		MN.Event.StopObserving(this._prefix + "_next","click",this.OnClickNext);
	}
	clearInterval(this._volIntvl);
	if (this._options.volume) 
	{
		MN.Event.StopObserving(this._volume,"ValueChanged",this.OnVolumeChange);
		MN.Event.StopObserving(this._volume,"SlideStart",this.OnStartVolumeScrub);
		MN.Event.StopObserving(this._volume,"SlideStop",this.OnStopVolumeScrub);
		// Currently this Destroy call invokes the function declared in this file, yet still does not completely
		// stop the mouse handlers correctly from the objects they are watching. Results are erratic until this can be fixed
		this._volume.Destroy();
		this._volume = null;
	}
	if (this._options.size)
	{
		MN.Event.StopObserving(this._prefix + "_size","click",this.OnClickSize);
	}
	if (this._options.live)
	{
		MN.Event.StopObserving(this._prefix + "_live","click",this.OnClickLive);
	}
	
	this._qmp = null;
	this.player = null;
}
// Wrapper to _qmp.Play function so we can keep track of current playing URL and check if it is already loaded. Calls Play
// normally if it isn't, but just sets the current position otherwise to avoid reloading stream
_mndvr.Play = function(url,start,end)
{	
	if (url!=null)
	{
		this._url = url;
	}
	if (this._qmp.CurrentQVT() == null || this._url != this._qmp.CurrentQVT().qvtURL)
	{
		this._qmp.Play(url,start,end);
	}
	else
	{
		if (this._playstate!=MN.QMP.PS.PLAYING)
			this._qmp.Play();
		if (start != null)
			this._qmp.CurrentPosition(start);
	}
}
// Moves scubber thumb on HSlider widget's track based on position
_mndvr.UpdateScrubber = function()
{
	if (this._qmp.Paused()) return;
	var pct = (this._qmp.CurrentPosition()/this._qmp.Duration()) * this._sliderSteps;
	if (!isNaN(pct)) this._slider.Value(pct);
}
// Updates text in position element to reflect current position and length of media
_mndvr.UpdatePosition = function()
{
	if (this._seeking)
	{
		var pos = parseInt(this._qmp.CurrentPosition(),10);
		if (pos==0)
		{
			this._qmp.StopScrubbing();
			this._scrubspeed = 0;
			this._seeking = false;
			this.UpdatePSDisplay();
		}
	}
	if (!this._scrubbing)
	{
		var val = MN.ConvertToTimestamp(this._qmp.CurrentPosition()) + " / " + MN.ConvertToTimestamp(this._qmp.Duration());
		MN.SetInnerText($(this._prefix + "_position"),val);
	}
	this._curpos = this._qmp.CurrentPosition();
}
// Displays the position of the seek time while moving the timeline scrubber
_mndvr.OnMoveScrubber = function(value)
{
	if (this._options.position)
	{
		var pos = this._qmp.Duration() * (value/this._sliderSteps);
		MN.SetInnerText($(this._prefix + "_position"),MN.ConvertToTimestamp(pos) + " / " + MN.ConvertToTimestamp(this._qmp.Duration()));
	}
}
_mndvr.OnStartScrub = function()
{
	this._qmp.Paused(true);
	this._scrubbing = true;
}
// When the user lets go of scrubber, gets the position they requested and either sets the
// player's position or fires the 'StopScrub' event to be handled outside of the object
// to do things such as display advertisments or other abitrary code and then set the position later
_mndvr.OnStopScrub = function()
{
	this._qmp.Paused(false);
	this._scrubbing = false;
	var pos = this._qmp.Duration() * (this._slider.Value()/this._sliderSteps);
	if (this._options.handleScrub==null||this._options.handleScrub)
	{
		this._qmp.CurrentPosition(pos);
	}
	else
	{
		this.FireEvent("StopScrub", pos);
	}
}
_mndvr.UpdateVolumeScrubber = function()
{
	if (!this._scrubbingvolume)
	{
		this._volumeVal = this._qmp.Volume();
		if (this._options.volume) 
		{
			this._volume.Value(this._volumeVal);
		}
	}
}
_mndvr.OnStartVolumeScrub = function()
{
	this._scrubbingvolume = true;
}
_mndvr.OnStopVolumeScrub = function()
{
	this._scrubbingvolume = false;
}
_mndvr.OnPSChanged = function(oldS, newS)
{
	this._playstate = newS;
	this.UpdatePSDisplay();
}
// Look up the _playstate value in the global PS string table and display to user and update the
// Play/Pause button to reflect the correct function
_mndvr.UpdatePSDisplay = function()
{
	if (this._options.playState) 
	{
		var stateStr = MN.QMP.PS[this._playstate];
		MN.SetInnerText($(this._prefix + "_status"),stateStr);
	}
	if (this._options.playPause)
	{
		// Commented out because was told button should not display Play when stream is stalled
		// if (this._playstate != MN.QMP.PS.PLAYING) this.TogglePlayPause(true);
		// else 
		this.TogglePlayPause();
	}
}
_mndvr.OnBRChanged = function(newBR)
{
	this._bitrate = newBR;
	this.UpdateBRDisplay();
}
_mndvr.UpdateBRDisplay = function()
{
	if (this._options.bitrate && !isNaN(this._bitrate))
	{
		MN.SetInnerText($(this._prefix + "_bitrate"),this._bitrate + "Kbps");
	}
}
_mndvr.Pause = function(b)
{
	if (this._playstate==MN.QMP.PS.PLAYING)
	{
		var paused = (b) ? !b : this._qmp.Paused();
		this._qmp.Paused(!paused);
		if (this._options.playState) 
		{
			MN.SetInnerText($(this._prefix + "_status"),(paused)?"Playing":"Paused");
		}
	}
}
// Handler for "*_playpause" element to either put or bring the media into a paused state. If the user was seeking,
// cancel and begin playing again.
_mndvr.OnClickPlayPause = function()
{
	if (this._playstate==MN.QMP.PS.PLAYING)
	{
		if (this._seeking)
		{
			this._qmp.StopScrubbing();
			this._scrubspeed = 0;
			this._seeking = false;
			this.TogglePlayPause(false);
			if (this._options.playState) 
			{
				MN.SetInnerText($(this._prefix + "_status"),MN.QMP.PS[3]);
			}
			return;
		}
		this.Pause();
	}
	else
	{
		var pos = (Math.ceil(this._curpos)==this._qmp.Duration())?0:this._curpos;
		this._qmp.CurrentPosition(pos);
	}
}
// This function takes an optional boolean parameter to change the class of the "*_playpause" element to either
// the play or pause display state. If you don't pass a value, it checks the current Paused() value of the player.
// If paused equals true, the "mn_pause" CSS class is applied to the element, otherwise the "mn_play" is.
// When the playPrefix option is set, the "mn_" part is replaced by the defined string.
_mndvr.TogglePlayPause = function(paused)
{
	if (paused==null)
	{
		paused = this._qmp.Paused();
	}
	if (this._options.playPause)
	{
		var playClass = (this._options.playPrefix)?"%splay".format(this._options.playPrefix):"mn_play";
		var pauseClass = (this._options.playPrefix)?"%spause".format(this._options.playPrefix):"mn_pause";
		MN.CSS.RemoveClass(this._prefix + "_playpause",(!paused)?playClass:pauseClass);
		MN.CSS.AddClass(this._prefix + "_playpause",(!paused)?pauseClass:playClass);
	}
}
// These next three functions are the handlers for the seeking functionality
_mndvr.OnClickRewind = function()
{
	this.DoSeek(false);
}
_mndvr.OnClickForward = function()
{
	if (this._qmp.Paused())
	{
		this._qmp.SingleStep();
		return;
	}
	this.DoSeek(true);
}
_mndvr.DoSeek = function(fwd)
{
	if ((this._scrubspeed < 0 && fwd) || (this._scrubspeed > 0 && !fwd)) this._scrubspeed = 0;
	if (this._scrubspeed==0)
		this._scrubspeed = 2;
	else if (Math.abs(this._scrubspeed)==16)
		return;
	else
		this._scrubspeed *= 2;
	this._scrubspeed = (fwd||this._scrubspeed<0)?this._scrubspeed:this._scrubspeed*-1;
	if (this._qmp.Scrub(this._scrubspeed))
	{
		this._seeking = true;
		this.TogglePlayPause(true);
		if (this._options.playState) 
		{
			var stateStr = "Seeking " + this._scrubspeed + "X";
			MN.SetInnerText($(this._prefix + "_status"),stateStr);
		}
	}
	else
	{
		this._qmp.StopScrubbing();
		this.TogglePlayPause(false);
		this._scrubspeed = 0;
	}
}
// These two functions are the handlers for skipping to the previous or next show in a QVT timeline.
// Nothing happens if there is not a show to skip to.
_mndvr.OnClickPrevious = function()
{
	var qvt = this._qmp.CurrentQVT();
	var showcount = qvt.ShowCount();
	if (showcount > 1)
	{
		var shownum = this._qmp.CurrentShow();
		if (shownum > 0)
		{
			var gotoShow = shownum;
			if ((this._qmp.CurrentPosition() - qvt.StartTime(shownum)) <= 2)
			{
				gotoShow--;
			}
			this._qmp.CurrentShow(gotoShow);
		}
	}
}
_mndvr.OnClickNext = function()
{
	var qvt = this._qmp.CurrentQVT();
	var showcount = qvt.ShowCount();
	if (showcount > 1)
	{
		var shownum = this._qmp.CurrentShow();
		if (shownum < showcount-1)
		{
			this._qmp.CurrentShow(shownum+1);
		}
	}
}
_mndvr.OnVolumeChange = function(value)
{
	this._volumeVal = value;
	if (value==0)
	{
		this._qmp.Muted(true);
	}
	else
	{
		this._qmp.Muted(false);
		this._qmp.Volume(value);
	}
}
// Handle the click of the sizing button, change the class of the control, and fire an event that can
// be caught by an outside handler to move and/or size the player container
_mndvr.OnClickSize = function()
{
	MN.CSS.RemoveClass(this._prefix + "_size",(!this._sizemax)?"mn_sizemax":"mn_sizemin");
	MN.CSS.AddClass(this._prefix + "_size",(!this._sizemax)?"mn_sizemin":"mn_sizemax");
	this._sizemax = (!this._sizemax);
	this.FireEvent("PlayerSized", this._sizemax);
}
// Handle the click of the live button and set the current position to -1, which when the stream is live,
// moves to the latest available streamlet
_mndvr.OnClickLive = function()
{
	this._qmp.CurrentPosition(-1);
}
_mndvr.CurrentURL = function() { return this._url; }
_mndvr.Player = function() { return this._qmp; }

delete _mndvr;

// These functions are an attempt to extend the MN classes to remove the handlers watching the mouse events on a widget.
// Currently does not work and needs to be improved. This is to stop the sliders from incorrectly handling the thumb
// element after the DVR object is destroyed and a new one tries to watch the same slider.
MN.Widget.RemoveMouseHandlers = function(elOrID)
{
	wrappedMoveHandler = function(e){}
	wrappedUpHandler = function(e){}
	wrappedDownHandler = function(e){}
	MN.Event.StopObserving(document, 'mousemove', wrappedMoveHandler);
	MN.Event.StopObserving(document, 'mouseup', wrappedUpHandler);
	MN.Event.StopObserving($(elOrID), 'mousedown', wrappedDownHandler);
}
MN.Widget.HSlider.prototype.Destroy = function()
{
	MN.Widget.RemoveMouseHandlers(this.track);
}

//**************************************************************************
var ButtonState = 
{
	SetupButton : function(id)
	{
		var btn = $(id);
		if (btn != null)
		{
			var btn_height = parseInt(btn.getAttribute("but_height"),10);
			btn.style.height = "%spx".format(btn_height*2);
			btn.parentNode.style.height = "%spx".format(btn_height);
		
			//log("XXXXXXXXXXX btn.style.height = %s".format(btn.style.height));
	
			btn.onmouseover = function()
			{
				var mode = this.getAttribute("but_mode");
				if (mode == null || mode == "on")
				{
					this.style.top = "-%spx".format(btn_height);
				}
			}
	
			btn.onmouseout = function()
			{
				var mode = this.getAttribute("but_mode");
				if (mode == null || mode == "on")
				{
					this.style.top = "0px";
				}
			}
		}
	},

	RegisterButtons : function(obj)
	{
		if (obj==null) obj = document.body;
		var children = obj.childNodes;
		for (var x=0; x < children.length; x++)
		{
			var child = children[x];
			if (child.nodeType==1)
			{
				var but_height = child.getAttribute("but_height");
				if (but_height != null)
				{
					ButtonState.SetupButton(child);
				}
				if (child.childNodes.length > 0)
				{
					ButtonState.RegisterButtons(child);
				}
			}
		}
	},
	
	SetState : function(butid,stateOff)
	{
		var button = $(butid);
		button.setAttribute("but_mode",(stateOff)?"off":"on");
		if (stateOff)
		{
			var btn_height = button.getAttribute("but_height");
			button.style.top = "-%spx".format(btn_height);
		}
		else
		{
			button.style.top = "0px";
		}
	}
}


/************************************************************************************/
/* función para crear un objeto HTTP ************************************************/
/************************************************************************************/
function createXMLHttp() {
	if( typeof XMLHttpRequest != "undefined" ) {
		return new XMLHttpRequest();
	}
	else if( window.ActiveXObject) {
		var aVersions = [ 
			"MSXML2.XMLHttp.5.0",
			"MSXML2.XMLHttp.4.0",
			"MSXML2.XMLHttp.3.0",
			"MSXML2.XMLHttp",
			"Microsoft.XMLHttp"
		];
		for( var i = 0; i < aVersions.length; i++ ) {
			try {
				var oXmlHttp = new ActiveXObject( aVersions[i] );
				return oXmlHttp;
			}
			catch ( oError ) {
				// Error
			}
		}
	}
	throw new Error("El objecto XMLHttp no pudo ser creado");
}

var xmlHttpResult = null;
var xmlHttpError = null;
/********************************************************************************************************************
 * Función que realiza conexión HTTP y regresa el código HTML, después ejecuta la función enviada como parámetro	*
 * 'execute' si no se envía el parámetro el resultado del httprequest se insertará en el div con el id del parámetro*
 * domObject. IS																									*
 ********************************************************************************************************************/
function getNewAdRequest( action ) {
	var oXmlHttp = createXMLHttp();
	oXmlHttp.open("get", action, true);	
	oXmlHttp.onreadystatechange = function () {
		if ( oXmlHttp.readyState == 4 ) {
			if( oXmlHttp.status == 200 ) {
				xmlHttpResult = oXmlHttp.responseText;
				eval(xmlHttpResult);
				objPlayer.AdRefreshed();
			}	
			else {	
				xmlHttpError = "Error ID : " + oXmlHttp.status + "\nDescripción : " + oXmlHttp.responseText;
				if( parseInt(oXmlHttp.status) == 404 )
					alert('No se ha encontrado el archivo adServerProxy.php en este directorio\nPor favor incluyalo para poder recibir respuesta de Adserver');
				else
					alert(xmlHttpError);
				xmlHttpResult = "*** ERROR *** <br/><a href='javascript:alert(xmlHttpError);'>Ver detalle</a>";
				objPlayer.AdRefreshed();
			}
		}
	};
	oXmlHttp.send(null);
}
//*******************************************************************************************************
// Clases para insertar el player ***********************************************************************
//*******************************************************************************************************
var publicLockKey = 'YAOUIVJOBKJWGLPSEBCJ'+'JLOSAPWLMAQOPGHDGLPZ'+'ILISKKJSMPOEAJSWJLO'+'DOPOSRKJSAPQAGJHYHGFD';
var AdServerResponse = null;
var cuboInterval = null;
//Clase MovePlayer crea un objeto para controlar el player de move
//function MovePlayer( qvtURL, thumbnailImage, permaLinkUrl, playerSize, playerBorder, controlsBorder, adBorder, videoTitle, activateConsole ) {
function MovePlayer( videoParams ) {	
	this.width = null;
	this.height = null;
	this.thumbnail = null;
	this.id = null;
	this.videoURL = null;
	this.dimentionsArray = [];
	this.preRollAd = null;
	this.postRollAd = null;
	this.midRollAd = null;
	this.inAd = false;
	this.hasStarted = false;
	this.geoBlocked = false;
	this.isLive = false;
	this.duration = null;
	this.showTitle = null;
	this.showNumber = null;
	this.epgArray = [];
	this.toolNamesArray = [ 
		/*'playerContainer',*/
		'player1',  
		'videoBackground', 
		'videoPlay', 
		'videoTools', 
		'videoShare', 
		'videoPermalink', 
		'videoNoDisponible',
		'videoNoDisponibleUsa',
		'videoMessage',
		'videoEmbed'
	];
	
	//Variables para manejar publicidad
	this.preRollPlayed = false;
	this.postRollPlayed = false;
	this.AdResponse = [];
	this.adRequestPath = "";
	this.refreshedAdAction = null;
	this.adSite = null;
	this.adChannel = null;
	this.adSubchannel = null;
	this.adSize = null;
	this.adTile = null;
	this.adZone = null;
	this.adOrd = null;
	this.adType = 'ADS'; //ADS, DFP, OAD
	this.adDuration = null;
	this.onEndCurtainFunction = null;
	this.companionRefreshTime = 30000;//Miliseconds
	this.companionPausesPerClip = 0;
	this.adActive = { preroll: 1, midroll: 0, postroll: 0, telon: 0, companion: 0, cube: 0 }; //Llamados a Adserver
	this.adsDemoMode = false;
	this.userCountry = '';
	this.userCity = '';
	this.userState = '';
	this.Skin = null;
	
	//Funciones externas a ejecutarse
	this.sendToFriendFunction = null;
	this.permalinkFunction = null;
	this.maximizeFunction = null;
	this.onVideoEndedFunction = null;
	this.onShowChangedFunction = null;
	this.epgFunction = null;
	
	this.permalinkURL = null;
	this.playerDimentions = '320x240';
	this.consoleActive = false;
	this.paused = false;
	this.hasEnded = false;
	this.title = '';
	this.currentAdPosition = null;
	this.videoResumePosition = 0;
	this.hash = null;
	this.disableVideoLog = false;
	
	//Se definen los valores de Geolocalización del usuario
	if( gVideoValues.keyServer ) {
		this.userCountry = gVideoValues.keyServer.country;
		this.userState = gVideoValues.keyServer.state;
		this.userCity = gVideoValues.keyServer.city;
	}
	//Se valida la consola
	if( videoParams.console ) {
		this.consoleActive = true;
		$('playerDebugConsole').style.visibility = 'visible';
	}
	//Se definen los colores base de los bordes
	this.controlsBorderColor = '#000000';
	this.playerBorderColor = '#000000';
	this.adBackgroundColor = '#FF0000';
	//Permalink del video
	if( videoParams.permalink ) {
		this.permalinkURL = videoParams.permalink;
		if( this.permalinkURL.indexOf('embed.php') != -1 ) {
			this.id = this.permalinkURL.substring( this.permalinkURL.indexOf('id=') + 3, this.permalinkURL.indexOf('id=') + 8 );
			if( this.id.length == 5 )
				this.id = '0' + this.id;
		}
		else {
			if( this.permalinkURL.charAt( this.permalinkURL.length - 1 ) == '/' )
				this.permalinkURL = this.permalinkURL.substring( 0, this.permalinkURL.length - 1 );
			this.id = this.permalinkURL.substring( this.permalinkURL.lastIndexOf('/') - 6, this.permalinkURL.lastIndexOf('/') );
		}
	}
	//Si se mandan los colores como parámetros se sustituyen
	if( videoParams.controlsBorder )
		this.controlsBorderColor = videoParams.controlsBorder;
	if( videoParams.playerBorder )
		this.playerBorderColor = videoParams.playerBorder;
	if( videoParams.qvtURL ) {
		this.videoURL = videoParams.qvtURL;
		//Validamos si el video es Live Feed
		if( this.videoURL.indexOf("/feed/") != -1 )
			this.videoResumePosition = -1;
	}
	if( videoParams.adBorder )
		this.adBackgroundColor = videoParams.adBorder;
	//Se cambian los colores de los bordes
	$('clickToLinkAds').style.backgroundColor = this.adBackgroundColor;
	$('videoControls').style.borderColor = this.controlsBorderColor;
	$('playerContainer').style.borderColor = this.playerBorderColor;
	if( videoParams.thumbnail ) {
		this.thumbnail = videoParams.thumbnail;
		$('videoBackgroundImg').src = this.thumbnail;
	}
	if(	videoParams.title )
		this.title = videoParams.title;
	if(!MN.QMPInstall.CanPlay()) {
		$('videoPlay').style.visibility = 'hidden';
		$('player1').style.visibility = 'visible';
	}
	else
		$('videoPlay').style.visibility = 'visible';
	
	$('clickToLinkAds').style.display = 'none';
	$('controls1').style.display = 'none';
	//Cambiar el URL del video a reproducirse
	this.SetVideoUrl = function( videoUrl ) {
		if( videoUrl ) {
			this.videoURL = videoUrl;
			return true;
		}
		else
			return false;
	}
	//Cambiar el titulo del video
	this.SetVideoTitle = function( strTitle ) {
		if( strTitle ) {
			this.title = strTitle;
			return true;
		}
		else
			return false;
	}
	//Definir funcion al ejecutarse al obtener EPG
	this.SetEpgFunction = function( epgFunction ) {
		this.epgFunction = epgFunction;
	}
	//EPG
	this.EPG = function() {
		if( this.epgFunction )
			eval( this.epgFunction ); 
	}
	//Definir el valor para adserver
	this.SetAdValues = function( site, channel, subchannel, size, tile ) {
		this.adType = 'ADS';
		if( site )
			this.adSite = site;
		if( channel )	
			this.adChannel = channel;
		if( subchannel )
			this.adSubchannel = subchannel;
		if( size )
			this.adSize = size;
		if( tile )
			this.adTile = tile;
	}
	this.SetDFPValues = function( site, zone, size, tile, ord, configuration ) {
		this.adType = 'DFP';
		var adParams = null;
		if( site )
			this.adSite = site;
		if( zone ) {
			if( zone.indexOf('|') != -1 ) {
				adParams = zone.substring( zone.indexOf('|') + 1, zone.length );
				zone = zone.substring( 0, zone.indexOf('|') )
			}
			this.adZone = zone;
		}
		if( size )
			this.adSize = size;
		if( tile )
			this.adTile = tile;
		if( ord )
			this.adOrd = ord;
		if( configuration )
			adParams = configuration;
		if( adParams && adParams.length == 5 )	 {
			this.adActive = { preroll: parseInt(adParams.charAt(0)), midroll: parseInt(adParams.charAt(1)), postroll: parseInt(adParams.charAt(2)), telon: parseInt(adParams.charAt(3)), cube: parseInt(adParams.charAt(4)), companion: 0 }; //Llamados a Adserver
		}
	}
	//Ajustar el tamaño del player y sus elementos
	this.SetSize = function( dimentions ) {
		//alert('SetSize');
		if( !dimentions )
			dimentions = '320x240';
		this.dimentionsArray = dimentions.split("x");
		this.width = parseInt(this.dimentionsArray[0]);
		this.height = parseInt(this.dimentionsArray[1]);
		//Redimensionamos los tools y el player
		for(var i = 0; i < this.toolNamesArray.length; i++) {
			$( this.toolNamesArray[i] ).style.width = this.width-53 + 'px';
			$( this.toolNamesArray[i] ).style.height = this.height-40  + 'px';
		}
		$('videoControls').style.width = this.width + 'px';
		$('controls1').style.width = this.width + 'px';
		$('videoLoading').style.width = (this.width - 13) + 'px';
		if( $('companionTextLink') )
			$('companionTextLink').style.width = (this.width + 2) + 'px';
		//Si el player es pequeño desactivamos opciones de los controles
		$('plyr1_status').style.display = 'none';
		if( this.width <= 355 ) {
			//$('plyr1_position').style.display = 'none';
			$('plyr1_bitrate').style.display = 'none';
			$('videoToolsPermalink').style.display = 'none';
			if( this.width < 300 ) {
				$('plyr1_track').style.width = '102px';
				$('plyr1_position').style.width = '102px';
			}
		}
		else {
			$('plyr1_bitrate').style.display = 'block';
		}
		return true;
	}
	//Redimensionamos el player
	if( videoParams.dimentions ) 
		this.playerDimentions = videoParams.dimentions;
	this.SetSize( this.playerDimentions );
	//Función para definir el path de llamado a Adserver
	this.SetAdRequestPath = function( path ) {
		if( path ) {
			this.adRequestPath = path;
			return true;
		}
		else
			return false;
	}
	//Definimos tiempo de refresh de banner
	this.SetCompanionRefreshTime = function( time ) {
		this.companionRefreshTime = time * 1000;
	}
	//Definir funcion onshowchange
	this.SetOnShowChangedFunction = function( funcion ) {
		if( funcion )
			this.onShowChangedFunction = funcion;
		else 
			return false;
	}
	//Obtener un objeto de ad
	this.GetAdByType = function( type ) {
		for( var i = 0; i < this.AdResponse.length; i++ ) {
			if( this.AdResponse[i].adPosition == type )
				return this.AdResponse[i];
		}
		return false;
	}
	this.GetVideoAd = function( type ) {
		return this.GetAdByType( type );
	}
	this.GetCompanionBanner = function() {
		return this.GetAdByType( "COMPANION" );
	}
	this.GetTextLink = function() {
		return this.GetAdByType( "TEXTLINK" );
	}
	//Buscamos un tipo específico de Ad
	this.TypeInAd = function( type ) {
		var returnValue = false;
		for( var i = 0; i < this.AdResponse.length; i++ ) {
			if( this.AdResponse[i].adPosition == type ) {
				returnValue = true;
				break;
			}
		}
		return returnValue;
	}
	//Funciones para buscar un tipo de banner
	this.HasPreroll = function() {
		return this.TypeInAd( "PREROLL" );
	}
	this.HasCortinilla = function() {
		return this.TypeInAd( "CORTINILLA" );
	}
	this.HasMidroll = function() {
		return this.TypeInAd( "MIDROLL" );
	}
	this.HasPostroll = function() {
		return this.TypeInAd( "POSTROLL" );
	}
	this.HasCompanion = function() {
		return this.TypeInAd( "COMPANION" );
	}
	this.HasTextLink = function() {
		return this.TypeInAd( "TEXTLINK" );
	}
	this.HasCurtain = function() {
		return this.TypeInAd( "TELON" );
	}
	this.videoClick = function() {
		window.open(this.AdResponse[this.playingNowIndex].adLink);
	}
	//Cambiamos el estátus del player según sea necesario
	this.ChangeStatus = function( strStatus ) {
		switch( strStatus ) {
			case "inAd":
				$('videoControls').style.borderColor = this.adBackgroundColor;
				$('playerContainer').style.borderColor = this.adBackgroundColor;
				$('controls1').style.display = 'none';
				$('clickToLinkAds').style.display = 'block';
				if( this.consoleActive )
					$('playerDebugConsole').innerHTML += '************************* Reproduciendo Anuncio ***************************<br>';
			break;
			case "loading":
				$('videoLoading').style.display = 'block';
				$('controls1').style.display = 'none';
				$('clickToLinkAds').style.display = 'none';
				//alert('loading');
			break;
			case "notLoading":
				$('videoLoading').style.display = 'none';
			break;
			case "noControls":
				$('controls1').style.display = 'none';
			break;
			case "controls":
				$('controls1').style.display = 'block';
			break;
			case "inactive":
				$('controls1').style.display = 'none';
				$('player1').style.visibility = 'hidden';
			break;
			case "active":
				$('controls1').style.display = 'block';
				$('player1').style.visibility = 'visible';
			break;
			case "playing":
				$('videoControls').style.borderColor = this.controlsBorderColor;
				$('playerContainer').style.borderColor = this.playerBorderColor;
				$('controls1').style.display = 'block';
				$('clickToLinkAds').style.display = 'none';
				if( this.consoleActive )
					$('playerDebugConsole').innerHTML += '************************** Reproduciendo Video ***************************<br>';
			break;
			default:
			break;
		}
	}
	this.SetHash = function() {
		var strHash = '';
		var randomNumber = null;
		var start = null;
		var total = null;
		for ( i = 0; i < 39; i++ ) {
			randomNumber = Math.round( Math.random() * 2 ) + 1;
			if( randomNumber == 1 ) {
				start = 65;
				total = 25;
			}
			else if( randomNumber == 2 ) {
				start = 97;
				total = 25;
			}
			else {
				start = 48;
				total = 9;
			}
			strHash += String.fromCharCode(start + Math.round(Math.random() * total));
		}
		this.hash = strHash;
	}
	this.SetHash();
	this.BusIntellLog = function( action ) {
		if( !this.disableVideoLog ) {
			var imageLog = new Image();
			var urlLog = 'http://videolog.esmas.com/set_view.php';
			urlLog += '?action=' + action;
			urlLog += '&duration=' + Math.floor(this.duration);
			urlLog += '&cc=' + this.userCountry;
			urlLog += '&state=' + this.userState;
			urlLog += '&city=' + this.userCity;
			urlLog += '&url=' + escape(this.permalinkURL);		
			urlLog += '&hash=' + this.hash;
			urlLog += '&title=' + escape(this.title);
			if ( document.cookie.length > 0 ) {
				if( document.cookie.indexOf("esmasstats=") == -1 )  {
					var nd = new Date();
					document.cookie = "esmasstats="+(nd.getYear()+"").substring(2,4)+(((nd.getMonth()+1)<10)?"0":"")+(nd.getMonth()+1)+((nd.getDate()<10)?"0":"")+nd.getDate()+((nd.getHours()<10)?"0":"")+nd.getHours()+((nd.getMinutes()<10)?"0":"")+nd.getMinutes()+((nd.getSeconds()<10)?"0":"")+nd.getSeconds()+"-"+(Math.random()*1000000000000000000)+"-"+Math.round(Math.random()*100000000)+"; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
				}
				var begin = document.cookie.indexOf("esmasstats="); 	
				urlLog += '&CSIE=' + document.cookie.substring(begin + 11, begin + 50);
				if( document.cookie.indexOf("token=") != -1 )  {
					begin = document.cookie.indexOf("token="); 	
					urlLog += '&token=' + document.cookie.substring(begin + 6, begin + 42);				
				}
			}
			//urlLog += '&browser=' + escape(navigator.userAgent);
			//?token=18aaff5a-7c03-102c-8d25-0017a4aa18b4&IP=192.168.7.107&id_video=30125&promo=vive coca cola&cat=futbol&subcat=jornada1&date=2005-01-01 12:30:00&site=tvolucion&browser=IE&&sexo=F&CSIE=valorcookie
			//alert(urlLog);
			PrintOnConsole( urlLog, 'blue' );
			imageLog.src = urlLog;	
		}
		return true;
	}
	//Realizamos un request a Adserver
	this.RefreshAd = function( action, site, channel, subchannel, adsize, tile, position ) {
		AdServerResponse = null;	
		this.AdResponse = [];
		this.refreshedAdAction = action;
		var requestUrl = null;
		if( this.adsDemoMode ) {
			var number = Math.floor( Math.random() * parseInt(this.adZone) )+1;
			requestUrl = this.adRequestPath + this.adSite + '_' + position;
			if( position == 'cub' )
				requestUrl += '_' + number
			requestUrl += '.js?r=' + Math.random();
			getNewAdRequest( requestUrl );
		}
		else {
			switch( this.adType ) {
				case 'ADS':
					requestUrl = this.adRequestPath + '?site=' + this.adSite + '&categoria=' + this.adChannel + '&subcategoria=' + this.adSubchannel + '&adsize=' + this.adSize + '&roll=' + position + '&pais=' + this.userCountry;	
				break;
				case 'DFP':
					requestUrl = this.adRequestPath + '?site=' + this.adSite + '&zone=' + this.adZone + '&adsize=' + this.adSize + '&tile=' + this.adTile + '&ord=' + this.adOrd + '&roll=' + position + '&pais=' + this.userCountry + '&estado=' + escape(this.userState) + '&ciudad=' + escape(this.userCity) + '&id_video=' + this.id;
				break;
			}
			//alert('Adserver call: ' + requestUrl);
			//document.location.href = requestUrl;
			getNewAdRequest( requestUrl );
			PrintOnConsole( 'Ad ' + position.toUpperCase() + ': ' + requestUrl, 'yellow' );
		}
	}
	//Cuando el adserver termina el request llama esta función
	this.AdRefreshed = function() {
		if( AdServerResponse )
			this.AdResponse = AdServerResponse;
		eval( this.refreshedAdAction );
	}
	//Definir función a ejecutarse para mover el telón
	this.SetOnEndCurtainFunction = function( functionName ) {
		if( functionName ) {
			this.onEndCurtainFunction = functionName;
			return true;
		}
		else
			return false;
	}
	//Si el video no tiene preroll se busca un companion para que no quede vacío mientras sale un companion
	this.GetCompanionAlone = function() {
		if( this.adActive.cube == 1 )
			this.RefreshAd('this.PrintCompanion()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, 'cub');
	}
	//Obtenemos companion
	this.GetCompanion = function() {
		//alert(this.companionPausesPerClip);
		if( this.companionPausesPerClip > 0 ) {
			if( this.adActive.companion == 1 )
				this.RefreshAd('this.PrintCompanion()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, 'cub');
			this.companionPausesPerClip--;
			PrintOnConsole( "Cubos por mostrar: " + this.companionPausesPerClip );
		}
		else {
			if( !this.inAd ) {
				clearInterval(cuboInterval);
				PrintOnConsole( "Se resetea el contador del cubo" );
			}
		}
	}
	//Imprimimos companion
	this.PrintCompanion = function() {
		if( this.HasCompanion() ) {
			var companionAd = this.GetAdByType('COMPANION');
			if( companionAd.adType == 'IMAGE' ) {
				if( $('companionBanner') )
					$('companionBanner').innerHTML = '<a href="' + companionAd.adLink + '" target="_blank"><img src="' + companionAd.adImage.url + '" width="' + companionAd.adImage.width + '" height="' + companionAd.adImage.height + '" border="0"></a>';
			}
			else if( companionAd.adType == 'FLASH' ) {
				var outPut = '' +
				'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ID=flashad WIDTH=' + companionAd.adSwf.width + ' HEIGHT=' + companionAd.adSwf.height + '>' +
				'	<PARAM NAME=movie VALUE="' + companionAd.adSwf.url + '?clickTag=' + escape(companionAd.adLink) + '">' +
				'	<PARAM NAME=quality VALUE=autohigh>' +
				'	<PARAM NAME=wmode VALUE=transparent>' +
				'	<EMBED SRC="' + companionAd.adSwf.url + '?clickTag=' + escape(companionAd.adLink) + '" QUALITY=autohigh NAME=flashad swLiveConnect=TRUE WIDTH=' + companionAd.adSwf.width + ' HEIGHT=' + companionAd.adSwf.height + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" WMODE="transparent"></EMBED>' +
				'</OBJECT>';
				if( $('companionBanner') )
					$('companionBanner').innerHTML = outPut;
			}
		}
	}
	//Obtenemos telón
	this.GetCurtain = function( functionName ) {
		if( functionName )
			this.onEndCurtainFunction = functionName;
		this.RefreshAd('this.ShowCurtain()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, 'tel');
	}
	//Imprimimos telón
	this.ShowCurtain = function() {
		if( this.HasCurtain() ) {		
			var curtainAd = this.GetAdByType('TELON');
			if( curtainAd.adSwf ) {
				$('adCurtainUp').style.display = 'block';
				$('adCurtainUp').innerHTML = '' +
				'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ID=flashad WIDTH=' + curtainAd.adSwf.width + ' HEIGHT=' + curtainAd.adSwf.height + '>' +
				'	<PARAM NAME=movie VALUE="' + curtainAd.adSwf.url + '?clickTag=' + escape(curtainAd.adLink) + '">' +
				'	<PARAM NAME=quality VALUE=autohigh>' +
				'	<PARAM NAME=wmode VALUE=transparent>' +
				'	<EMBED SRC="' + curtainAd.adSwf.url + '?clickTag=' + escape(curtainAd.adLink) + '" QUALITY=autohigh NAME=flashad swLiveConnect=TRUE WIDTH=' + curtainAd.adSwf.width + ' HEIGHT=' + curtainAd.adSwf.height + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" WMODE="transparent"></EMBED>' +
				'</OBJECT>';
			}
			else {
				$('adCurtainLeft').style.backgroundImage = 'url(' + curtainAd.adImage[0].url + ')';
				$('adCurtainRight').style.backgroundImage = 'url(' + curtainAd.adImage[1].url + ')';
				$('adCurtainLeft').innerHTML = '<a href="' + curtainAd.adLink + '" target="_blank"><img src="' + curtainAd.adImage[0].url + '" width="' + curtainAd.adImage[0].width + '" height="' + curtainAd.adImage[0].height + '" border="0"></a>';
				$('adCurtainRight').innerHTML = '<a href="' + curtainAd.adLink + '" target="_blank"><img src="' + curtainAd.adImage[1].url + '" width="' + curtainAd.adImage[1].width + '" height="' + curtainAd.adImage[1].height + '" border="0"></a>';
			}
			if( this.onEndCurtainFunction )
				eval( this.onEndCurtainFunction );
			else
				alert( 'No se ha definido una función para abrir el telón' );
		}
		else {
			$('adCurtain').style.visibility = 'hidden';
			this.Play();
		}
	}
	//Obtenemos el código del banner preroll
	this.GetPreroll = function() {
		//_dvr.Player().Paused(true);
		var position = '';
		( this.duration > 59 || this.isLive ) ? position = 'pre' : position = 'cort';
		if( this.adActive.preroll == 1 )
			this.RefreshAd('this.PlayPreroll()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, position);
		else {
			this.AdResponse = [];
			this.PlayPreroll();
		}	
	}
	//Reproducimos el preroll
	this.PlayPreroll = function() {
		this.preRollPlayed = true;
		this.ChangeStatus( 'notLoading' );
		//Vemos si la respuesta del adserver trae ad
		if( this.HasPreroll() || this.HasCortinilla() ) {
			if( this.HasPreroll() )
				this.preRollAd = this.GetVideoAd('PREROLL');
			else
				this.preRollAd = this.GetVideoAd('CORTINILLA');
			PrintOnConsole('Preroll encontrado:' + this.preRollAd.adTitle);
			_dvr.Play(this.preRollAd.adURL, 0, null);
			$('clickToLinkAds').innerHTML = '<a href="' + this.preRollAd.adLink + '" target="_blank">' + this.preRollAd.adTitle + '</a>';
			if( this.preRollAd.adImage ) {
				if( $('companionBanner') )
					$('companionBanner').innerHTML = '<a href="' + this.preRollAd.adLink + '" target="_blank"><img src="' + this.preRollAd.adImage.url + '" width="' + this.preRollAd.adImage.width + '" height="' + this.preRollAd.adImage.height + '" border="0"></a>';
			}
			else if( this.preRollAd.adSwf ) {
				var outPut = '' +
				'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ID=flashad WIDTH=' + this.preRollAd.adSwf.width + ' HEIGHT=' + this.preRollAd.adSwf.height + '>' +
				'	<PARAM NAME=movie VALUE="' + this.preRollAd.adSwf.url + '?clickTag=' + escape(this.preRollAd.adLink) + '">' +
				'	<PARAM NAME=quality VALUE=autohigh>' +
				'	<PARAM NAME=wmode VALUE=transparent>' +
				'	<EMBED SRC="' + this.preRollAd.adSwf.url + '?clickTag=' + escape(this.preRollAd.adLink) + '" QUALITY=autohigh NAME=flashad swLiveConnect=TRUE WIDTH=' + this.preRollAd.adSwf.width + ' HEIGHT=' + this.preRollAd.adSwf.height + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" WMODE="transparent"></EMBED>' +
				'</OBJECT>';
				if( $('companionBanner') )
					$('companionBanner').innerHTML = outPut;
			}
			if( this.preRollAd.adSkin ) {
				if( this.Skin ) {
					this.Skin.top.style.backgroundImage = 'url(' + this.preRollAd.adSkin.top + ')';
					this.Skin.right.style.backgroundImage = 'url(' + this.preRollAd.adSkin.right + ')';
				}
			}	
			if( this.preRollAd.adExtImpression ) {
				var extImpression = new Image();
				extImpression.src = this.preRollAd.adExtImpression;
			}
			this.ChangeStatus("inAd");
			this.inAd = true;
		}
		//No hay Ad en la respuesta
		else {
			_dvr.Player().Paused(false);
			if( this.companionRefreshTime != 0 )
				this.GetCompanionAlone();
		}
		PrintOnConsole('Se lanza el contador del cubo');
		if( this.companionRefreshTime != 0 )
			cuboInterval = setInterval("objPlayer.GetCompanion()", this.companionRefreshTime);
		this.hasStarted = true;
		return true;
	}
	//Obtenemos banner de midroll
	this.GetMidroll = function() {
		_dvr.Player().Paused(true);
		if( this.adActive.midroll == 1 )
			this.RefreshAd('this.PlayMidroll()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, 'mid');
		else {
			this.AdResponse = [];
			this.PlayMidroll();
		}
	}
	//Reproducimos el midroll
	this.PlayMidroll = function() {
		if( this.HasMidroll() ) {
			$('playerDebugConsole').innerHTML += 'Se encontró un midroll...<br>';
			this.videoResumePosition = _dvr.Player().CurrentPosition() + this.adDuration;
			this.ChangeStatus( 'loading' );
			this.midRollAd = this.GetVideoAd('MIDROLL');
			//Marcamos cual fue el ultimo ad reproducido para cambiar los companions
			this.currentAdPosition = 'MIDROLL';
			//Reproducimos el Ad
			_dvr.Play(this.midRollAd.adURL, 0, null);
			$('clickToLinkAds').innerHTML = '<a href="' + this.midRollAd.adLink + '" target="_blank">' + this.midRollAd.adTitle + '</a>';
			if( this.midRollAd.adImage ) {
				if( $('companionBanner') )
					$('companionBanner').innerHTML = '<a href="' + this.midRollAd.adLink + '" target="_blank"><img src="' + this.midRollAd.adImage.url + '" width="' + this.midRollAd.adImage.width + '" height="' + this.midRollAd.adImage.height + '" border="0"></a>';
			}
			else if( this.midRollAd.adSwf ) {
				var outPut = '' +
				'<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" ID=flashad WIDTH=' + this.midRollAd.adSwf.width + ' HEIGHT=' + this.midRollAd.adSwf.height + '>' +
				'	<PARAM NAME=movie VALUE="' + this.midRollAd.adSwf.url + '?clickTag=' + escape(this.midRollAd.adLink) + '">' +
				'	<PARAM NAME=quality VALUE=autohigh>' +
				'	<PARAM NAME=wmode VALUE=transparent>' +
				'	<EMBED SRC="' + this.midRollAd.adSwf.url + '?clickTag=' + escape(this.midRollAd.adLink) + '" QUALITY=autohigh NAME=flashad swLiveConnect=TRUE WIDTH=' + this.midRollAd.adSwf.width + ' HEIGHT=' + this.midRollAd.adSwf.height + ' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" WMODE="transparent"></EMBED>' +
				'</OBJECT>';
				if( $('companionBanner') )
					$('companionBanner').innerHTML = outPut;
			}
			if( this.midRollAd.adSkin ) {
				if( this.Skin ) {
					this.Skin.top.style.backgroundImage = 'url(' + this.midRollAd.adSkin.top + ')';
					this.Skin.right.style.backgroundImage = 'url(' + this.midRollAd.adSkin.right + ')';
				}
			}
			this.ChangeStatus("inAd");
			this.inAd = true;
		}
		//Si no trae campaña de midroll que se brinque el espaacio del ad_dynamic
		else
			_dvr.Player().CurrentPosition( _dvr.Player().CurrentPosition() + this.adDuration );
		if( this.companionRefreshTime != 0 )
			cuboInterval = setInterval("objPlayer.GetCompanion()", this.companionRefreshTime);
		return true;
	}
	//Obtenemos banner de postroll
	this.GetPostroll = function() {
		_dvr.Player().Paused(true);
		if( this.adActive.postroll == 1 )
			this.RefreshAd('this.PlayPostroll()', this.adSite, this.adChannel, this.adSubchannel, this.adSize, this.adTile, 'post');
		else {
			this.AdResponse = [];
			this.PlayPostroll();
		}
	}
	//Reproducir Postroll
	this.PlayPostroll = function() {
		if( this.HasPostroll() ) {
			this.ChangeStatus( 'loading' );
			this.postRollAd = this.GetVideoAd('POSTROLL');
			//Marcamos cual fue el ultimo ad reproducido para cambiar los companions
			this.currentAdPosition = 'POSTROLL';
			//Reproducimos el Ad
			_dvr.Play(this.postRollAd.adURL, 0, null);
			$('clickToLinkAds').innerHTML = '<a href="' + this.postRollAd.adLink + '" target="_blank">' + this.postRollAd.adTitle + '</a>';
			if( $('companionBanner') )
				$('companionBanner').innerHTML = '<a href="' + this.postRollAd.adLink + '" target="_blank"><img src="' + this.postRollAd.adImage.url + '" width="' + this.postRollAd.adImage.width + '" height="' + this.postRollAd.adImage.height + '" border="0"></a>';
			this.ChangeStatus("inAd");
			this.inAd = true;
		}
		//El ad no trae postroll
		else
			this.Finished();
		this.postRollPlayed = true;
		return true;
	}
	//Si el usuario hace click en restart
	this.Restart = function() {
		this.Play();
		this.BusIntellLog('restart');
	}
	//Reproducir un video
	this.Play = function() {
		if( this.videoURL ) {
			this.hasEnded = false;
			if( this.videoURL.indexOf("/feed/") != -1 )
				this.videoResumePosition = -1;
			this.ChangeStatus( 'loading' );
			$('controls1').style.display = 'block';
			_dvr.Play(this.videoURL, this.videoResumePosition, null);
			$('videoPlay').style.visibility = 'hidden';
			$('player1').style.visibility = 'visible';
			return true;
		}
		else {
			alert('No hay video para reproducir');
			return false;
		}
	}
	//Si el video no está disponible por geoblocking
	this.VideoNotAvailable = function( country ) {
		_dvr.Player().Paused(true);
		$('player1').style.visibility = 'hidden';
		if( country == 'usa' )
			$('videoNoDisponibleUsa').style.visibility = 'visible';
		else
			$('videoNoDisponible').style.visibility = 'visible';
		$('controls1').style.display = 'none';
		this.ChangeStatus('notLoading');
	}
	
	//Cuando todo el set de reproducción ha terminado
	this.Finished = function() {
		if( this.onVideoEndedFunction )
			eval( this.onVideoEndedFunction );
		$('player1').style.visibility = 'hidden';
		$('videoTools').style.visibility = 'visible';
		this.ChangeStatus("playing");
		$('controls1').style.display = 'none';
		this.videoResumePosition = 0;
		this.hasEnded = true;
		this.BusIntellLog('end');
	}
	//Cuando termina un clip
	this.VideoEnded = function() {
		//Acaba de ejecutar un Ad
		if( this.inAd ) {
			//Si el ad que terminó es un postroll
			if( this.postRollPlayed )
				this.Finished();
			//Si es un pre,midroll
			else {
				this.ChangeStatus( 'loading' );
				_dvr.Player().CurrentPosition( this.videoResumePosition );
				_dvr.Play(this.videoURL, this.videoResumePosition, null);
				this.ChangeStatus( 'playing' );
			}
			this.inAd = false;
		}
		else {
			//Acabó el video, busca un postroll
			if( !this.postRollPlayed )
				this.GetPostroll();
			else
				this.Finished();
		}
		return true;
	}
	this.PlayAsAd = function( object ) {
		this.ChangeStatus( 'loading' );
		var adObject = null;
		if( object )
			adObject = object;
		else
			return false;
		_dvr.Play(adObject.adURL, 0, null);
		$('clickToLinkAds').innerHTML = '<a href="' + adObject.adLink + '" target="_blank">' + adObject.adTitle + '</a>';
		$('videoPlay').style.visibility = 'hidden';
		$('player1').style.visibility = 'visible';
		this.ChangeStatus("inAd");
	}
	//Pausar el player
	this.PausePlaying = function() {
		_dvr.Pause();
		$('videoTools').style.visibility = 'hidden';
		if( this.paused ) {
			$('player1').style.visibility = 'visible';
			$('videoPlay').style.visibility = 'hidden';
			this.paused = false;
			return true;
		}
		else{
			$('player1').style.visibility = 'hidden';
			$('videoPlay').style.visibility = 'visible';
			this.paused = true;
			return false;
		}
	}
	this.FullScreen = function() {
		if( this.maximizeFunction )
			eval( this.maximizeFunction );
		else 
			OnFullScreen();
		return true;
	}
	this.SetOnVideoEndedFunction = function( strFunction ) {
		if( strFunction ) {
			this.onVideoEndedFunction = strFunction;
			return true;
		}
		else
			return false;
	}
	this.SetMaximizeFunction = function( strFunction ) {
		if( strFunction ) {
			this.maximizeFunction = strFunction;
			return true;
		}
		else
			return false;
	}
	this.SetSendToFriendFunction = function( strFunction ) {
		if( strFunction ) {
			this.sendToFriendFunction = strFunction;
			return true;
		}
		else
			return false;
	}
	this.SetPermalinkFunction = function( strFunction ) {
		if( strFunction ) {
			this.permalinkFunction = strFunction;
			return true;
		}
		else
			return false;
	}
	this.CleanTools = function() {
		$('videoMessage').style.visibility = 'hidden';
		$('videoShare').style.visibility = 'hidden';
		$('videoPermalink').style.visibility = 'hidden';
		$('videoEmbed').style.visibility = 'hidden';
		$('videoTools').style.visibility = 'hidden';
	}
	this.ShowToolWindow = function( tool ) {
		if( !this.inAd ) {
			this.CleanTools();
			$(tool).style.visibility = 'visible';
			if( this.hasEnded )
				$('videoTools').style.visibility = 'hidden';
			else {
				_dvr.Player().Paused(true);
				this.ChangeStatus('inactive');
			}
		}
		return true;
	}
	this.HideToolWindow = function( tool ) {
		$(tool).style.visibility = 'hidden';
		if( this.hasEnded )
			$('videoTools').style.visibility = 'visible';
		else {
			_dvr.Player().Paused(false);
			this.ChangeStatus('active');
		}
	}
	this.ShowMessage = function( innerHtml ) {
		$('videoMessage').innerHTML = innerHtml;
		this.ShowToolWindow('videoMessage');
		return true;
	}
	this.HideMessage = function() {
		this.HideToolWindow('videoMessage');
	}
	this.SendToFriend = function() {
		if( !this.inAd ) {
			if( !this.sendToFriendFunction ) {
				var theForm = document.frmSendNote;
				theForm.userName.value = "Escribe aquí tu nombre";
				theForm.from.value = "Tu correo";
				theForm.to.value = "Correo de tu amigo";
				theForm.mensaje.value = "Escribe aquí tu mensaje";
				this.ShowToolWindow('videoShare');
			}
			else
				eval( this.sendToFriendFunction );
		}
		return true;
	}
	this.CancelSendFriend = function() {
		this.HideToolWindow('videoShare');
		$('videoShare').style.visibility = 'hidden';
	}
	this.ShowPermalink = function() {
		if( !this.permalinkFunction ) {
			if( this.permalinkURL )
				$('videoPermalinkTextarea').value = this.permalinkURL;
			else 
				$('videoPermalinkTextarea').value = document.location.href;
			this.ShowToolWindow('videoPermalink');
			$('videoPermalinkTextarea').focus();
			$('videoPermalinkTextarea').select();
		}
		else
			eval( this.permalinkFunction );
		return true;
	}
	this.HidePermalink = function() {
		this.HideToolWindow('videoPermalink');
		return true;
	}	
	
	this.ShowEmbed = function( videoId ) { 
		$('videoEmbedTextarea').value = '<scr' + 'ipt language="JavaS' + 'cript" src="http://www.tvolucion.com/embed/?id=' + videoId + '"></scr' + 'ipt>'
		this.ShowToolWindow('videoEmbed');
		$('videoEmbedTextarea').focus();
		$('videoEmbedTextarea').select();
		return true;
	}
	this.HideEmbed = function() {
		this.HideToolWindow('videoEmbed');
		return true;
	}	
	this.copyToClipboard = function( s ) {
		if( window.clipboardData && clipboardData.setData )
			clipboardData.setData("Text", s);
	}
	
	this.sendVideoToFriend = function() {
		var theForm = document.frmSendNote;
		if ( (theForm.userName.value == "") || (theForm.userName.value.indexOf('Escribe aqu') > -1) || 
			(theForm.from.value == "") || (theForm.from.value.indexOf('Tu correo') > -1) || 
			(theForm.to.value == "") || (theForm.to.value.indexOf('Correo de tu amigo') > -1) ) {
			alert('Por favor llena todos los datos');
			return false;
		}
		else {
			window.open('','SentToFriend','width=500,height=300');
			var strTema = '';
			strTema += '<div align="center">';
			strTema += '<div style="font:normal 13px/17px Verdana,Arial;width:490px;" align="center">';
			strTema += '	<a href="http://www.tvolucion.com" target="_blank"><img src="http://www.esmas.com/cosmosfiles/html/tv3/img/logomail.jpg" width="490" height="65" border="0"></a><br>';
			strTema += '	<ul style="list-style:none;width:490px;max-width:466px;margin:0;padding:12px;border:1px solid #D5D6D8;border-top:0;border-bottom:0;">';
			strTema += '		<li style="background-color:#BFE1EA;padding:8px;text-align:left;"><strong>' + theForm.userName.value + '</strong> quiere recomendarte el video <strong>' + this.title + '</strong> en Tvolucion, que seguro te va a interesar.</li>';
			strTema += '		<li style="padding:10px;text-align:center;"><a href="' + this.permalinkURL + '" target="_blank"><img src="' + this.thumbnail + '" border="0"></a></li>'; 
			if ( (theForm.mensaje.value != "") && (theForm.mensaje.value.indexOf('Escribe aqu') == -1) )
				strTema += '		<li style="background-color:#BFE1EA;padding:8px;text-align:left;"><strong>Mensaje de: </strong>' + theForm.userName.value + '<br><br>' + theForm.mensaje.value + '</li>';
			strTema += '		<li style="margin: 10px 0 0 0;text-align:center;border-bottom:1px solid #D5D6D8;padding:0 0 8px 0;">Haz clic en la liga para ver el video que te recomienda ' + theForm.userName.value + ':<br><a href="' + this.permalinkURL + '" style="color:#BFE1EA;text-decoration:none;font-weight:bold;" target="_blank">' + this.permalinkURL + '</a><br>Ahí podrás disfrutar de este y miles de videos más <br>que tenemos para ti, con lo mejor de Tvolucion.</li>';
			strTema += '		<li style="margin: 10px 0 0 0;text-align:center;border-bottom:1px solid #D5D6D8;padding:0 0 8px 0;font:normal 11px/15px Verdana,Arial;"><strong>¿Aún no eres miembro de Mi Página? Haz clic en la liga para registrarte con nosotros</strong> <a href="http://mipagina.esmas.com/register1.php" style="color:#BFE1EA;text-decoration:none;font-weight:bold;" target="_blank">http://mipagina.esmas.com/register1.php</a><br>Siendo miembro de Esmas podrás crear tu perfil, subir tus imágenes, videos y hacer cientos de amigos.</li>';
			strTema += '	</ul>';
			strTema += '	<a href="http://www.tvolucion.com" target="_blank"><img src="http://www.esmas.com/cosmosfiles/html/tv3/img/BaseShadow.jpg" width="490" height="11" border="0"></a><br>';
			strTema += '	<ul style="list-style:none;width:490px;max-width:466px;margin:0;padding:12px;">';
			strTema += '		<li style="margin: 10px 0 0 0;text-align:center;font:normal 11px/15px Verdana,Arial;">Si crees que recibiste este correo por equivocación o tienes alguna duda o pregunta respecto a nuestra Política de Privacidad, por favor contáctanos en: <a href="mailto:privacidad@esmas.com" style="color:#BFE1EA;text-decoration:none;font-weight:bold;">privacidad@esmas.com</a></li>';
			strTema += '		<li style="margin: 15px 0 0 0;text-align:center;font:normal 11px/15px Verdana,Arial;">2009 Esmas.com. Todos los derechos reservados.</li>';
			strTema += '	</ul>';
			strTema += '</div>';
			strTema += '</div>';
			//strTema += "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>";
			//strTema += "<html><head><title>Recomendacion</title></head><body>";
			theForm.content.value = strTema; 
			this.CancelSendFriend();
			return true;
		}   	
	}
	this.GetThumbnail = function() {
		return this.thumbnail;
	}
}
function InsertMovePlayer() {
	document.write('<div id="playerContainer"></div>');
	document.write('<div id="videoControls"></div>');
}

var objPlayer = null;

//************************* MOVE *****************************************************************************

var _dvr = null;
//Objeto para Addynamics
var _adhelper = null;
// This function tells the SDK which version of the player to use and require and makes the call to create the
// object within the browser. The 'MN.QVT.CreatePlayer' call handles all of the work for detecting the version
// of the plugin and prompting the user to install if necessary.
var videoControlsContent = null;
var videoInitialParams = null;

function Init()
{
	var divContent = '' +
	'<div id="videoBackground"><img id="videoBackgroundImg" src="http://i.esmas.com/img/spacer.gif" class="backGround"></div>' +
	'<div id="videoPlay"><a href="javascript:void(null);" onclick="objPlayer.Play();"><img id="toolsButtonPlay" src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_play_video.png" width="86" height="86" alt="" border="0"></a></div>' +
	'<div id="videoTools">' +
	'	<a href="javascript:void(null);" onclick="objPlayer.Restart();"><img id="toolsButtonPlayAgain" src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_repetir_video.png" width="86" height="105" alt="" border="0"></a>' +
	'	<a href="javascript:void(null);" onclick="objPlayer.SendToFriend();"><img id="toolsButtonShare" src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_compartir_video.png" width="86" height="105" alt="" border="0"></a>' +
	'	<a href="javascript:void(null);" onclick="objPlayer.ShowPermalink();" id="videoToolsPermalink"><img id="toolsButtonPermalink" src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_permalink_video.png" width="86" height="105" alt="" border="0"></a>' +
	'</div>' +
	'<div id="videoShare">' +
	'<form action="http://mailer.esmasserver.com/servlet/sendEmail" method="post" name="frmSendNote" id="frmSendNote" onsubmit="return objPlayer.sendVideoToFriend()" target="SentToFriend">' +
	'<input Type="Hidden" Name="URLext" value="http://www.esmas.com/cosmosfiles/html/tv3/videoEnviado.html">' +
	'<input type="Hidden" name="sub" value="Video recomendado">' +
	'<input type="Hidden" name="content" value="">' +
	'	<ul>' +
	'		<li class="caja"><input name="userName" type="text" value="Escribe aqu&iacute; tu nombre" onclick="if(this.value.indexOf(\'Escribe aqu\')==0){this.value=\'\'}" onblur="if(this.value == \'\'){this.value=\'Escribe aquí tu nombre\'};"/></li>' +	
	'		<li class="caja"><input name="from" type="text" value="Tu correo" onclick="if(this.value.indexOf(\'Tu correo\')==0){this.value=\'\'}" onblur="if(this.value == \'\'){this.value=\'Tu correo\'};"/></li>' +		
	'		<li class="caja"><input name="to" type="text" value="Correo de tu amigo" onclick="if(this.value.indexOf(\'Correo de tu amigo\')==0){this.value=\'\'}" onblur="if(this.value == \'\'){this.value=\'Correo de tu amigo\'};"/></li>' +		
	'		<li class="caja"><textarea name="mensaje" cols="55" rows="5" onclick="if(this.value.indexOf(\'Escribe aqu\')==0){this.value=\'\'}" onblur="if(this.value == \'\'){this.value=\'Escribe aquí tu mensaje\'};" onfocus="this.select();">Escribe aqu&iacute; tu mensaje</textarea></li>' +
	'		<li class="botones"><input type="Submit" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_enviar.gif\'); height: 24px; width: 54px; background-color: transparent; border: 0; margin: 5px 5px 0 0;" value="";><input type="Button" value="" onclick="objPlayer.CancelSendFriend();" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_cancelar.gif\'); height: 24px; width: 67px; background-color: transparent; border: 0; margin: 0;"></li>' +
	'	</ul>' +
	'</form>' +
	'</div>' +
	'<div id="videoPermalink">' +
	'	<ul>'+
	'		<li class="titulo"><!--Link Permanente--></li>'+
	'		<li class="textos">Para poder acceder directamente al contenido de este video, copia el URL que se muestra abajo</li>'+
	'		<li class="caja"><textarea id="videoPermalinkTextarea"></textarea><br><input type="Button" value="" onclick="objPlayer.copyToClipboard(document.getElementById(\'videoPermalinkTextarea\').value);" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_codigo.gif\'); height: 24px; width: 96px; background-color: transparent; border: 0; margin: 3px 5px 0 0;"><input type="Button" value="" onclick="objPlayer.HidePermalink();" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_cancelar.gif\'); height: 24px; width: 67px; background-color: transparent; border: 0; margin: 3px 0 0 0;"></li>' +
	'	</ul>'+
	'</div>' +
	'<div id="videoEmbed">' +
	'	<ul>'+
	'		<li class="titulo"><!--Embed--></li>'+
	'		<li class="textos">Copia el código de la caja de texto y pegalo<br>en tu página personal o blog</li>'+
	'		<li class="caja"><textarea id="videoEmbedTextarea"></textarea><br><input type="Button" value="" onclick="objPlayer.copyToClipboard(document.getElementById(\'videoEmbedTextarea\').value);" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_codigo.gif\'); height: 24px; width: 96px; background-color: transparent; border: 0; margin: 3px 5px 0 0;"><input type="Button" value="" onclick="objPlayer.HideEmbed();" style="background-image: url(\'http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/tools/tool_btn_cancelar.gif\'); height: 24px; width: 67px; background-color: transparent; border: 0; margin: 3px 0 0 0;"></li>' +
	'	</ul>'+
	'</div>' +
	'<div id="videoMessage">-</div>' +
	'<div id="videoNoDisponible"><a href="http://www.esmas.com/cosmosfiles/move_player/geofilter/pais/index.html" target="_blank"><img src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/geoblock/warning_nodisponible_pais.jpg" width="250" height="170" alt="" border="0"></a></div>' +
	'<div id="videoNoDisponibleUsa"><a href="http://www.esmas.com/cosmosfiles/move_player/geofilter/eu/index.html" target="_blank"><img src="http://www.esmas.com/cosmosfiles/move_player/images/dvr_tv3/geoblock/warning_nodisponible_eua.jpg" width="250" height="170" alt="" border="0"></a></div>' +
	'<div id="player1"></div>';
	$('playerContainer').innerHTML = divContent;
	
	divContent = '' +
	'<div id="videoLoading"><img src="http://www.esmas.com/cosmosfiles/move_player/images/loader.gif" width="16" height="16" alt="" border="0" align="absmiddle"><span id="videoLoadingMsg">Cargando video, por favor espere</span></div>' +
	'<div id="clickToLinkAds"></div>' +
	'<div id="controls1" class="mn_control_panel">' +
	'	<table cellspacing="0" cellpadding="0" width="100%" border="0">' +
	'		<tr>' +
	'		<td class="mn_control_panel bg png">' +
	'			<table cellspacing="0" cellpadding="0" width="100%" border="0">' +
	'				<col width="27"/><col width="27"/><col width="40"/>' +
	'				<col width="27"/><col width="27"/><col/>' +
	'				<col width="110"/><col width="65"/><col width="75"/>' +
	'				<col width="65"/><col width="19"/>' +
	'				<tr>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +	
	'				<td><div class="button_container"><div class="button_view"><div id="plyr1_rew" but_height="34" class="button_canvas mn_rewind"></div></div></div></td>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +
	'				<td><div class="button_container width40"><div class="button_view"><div id="plyr1_playpause" but_height="34" class="button_canvas mn_pause"></div></div></div></td>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +
	'				<td><div class="button_container"><div class="button_view"><div id="plyr1_fwd" but_height="34" class="button_canvas mn_fast_forward"></div></div></div></td>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +	
	'				<td align="center"><div id="plyr1_position" class="mn_player_status">00:00 / 00:00</div><div id="plyr1_track" class="mn_timeline png">' +
	'					<div id="plyr1_track_thumb" class="mn_timeline_scrubber png"></div>' +
	'				</div></td>' +
	'				<td><div id="plyr1_status" class="mn_player_status">clic play</div></td>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +
	'				<td><div id="plyr1_bitrate" class="mn_player_status_bit_rate"></div></td>' +
	'				<td class="separador"><img src="http://i.esmas.com/img/univ/spacer.gif"></td>' +
	'				<td><div id="plyr1_volume" class="mn_volume png">' +
	'					<div class="button_container width19"><div class="button_view"><div id="plyr1_vol_thumb" but_height="6" class="button_canvas mn_vol_scrubber"></div></div></div>' +
	'				</div></td>' +
	'				</tr>' +
	'			</table>' +
	'		</td>' +	
	'</tr>' +
	'	</table>' +
	'</div>' +
	'<div id="playerDebugConsole" onclick="if(confirm(\'Desea cerrar la consola?\')){this.style.visibility=\'hidden\'}"></div>';
	if( videoControlsContent ) 
		$('videoControls').innerHTML = videoControlsContent;
	else
		$('videoControls').innerHTML = divContent;
	
	if(!MN.QMPInstall.CanPlay()){
		$('player1').style.visibility = 'visible';
		//$('player1').innerHTML = '<a id="customInstall" href="http://www.esmas.com/cosmosfiles/move_player/custominstall/index.html" onclick="window.open(this.getAttribute(\'href\'),\'popup\',\'width=670,height=700,status=yes,scrollbars=yes,resizable=no,location=no,toolbar=no\');return false;"><img src="http://www.esmas.com/cosmosfiles/move_player/custominstall/images/install/install.jpg" id="customInstallImg" width="250" height="170" alt="instalar" style=" padding 0;" border="0" /></a></div>';
		//$('player1').innerHTML = '<a id="customInstall" href="custominstall/install_1.html"><img src="custominstall/images/install/install.jpg" id="customInstallImg" width="250" height="170" alt="instalar" style="padding 0;" border="0"; /></a></div>';
		$('player1').innerHTML = '<a id="customInstall" href="http://www.esmas.com/cosmosfiles/move_player/custominstall/install_1.html"><img src="http://www.esmas.com/cosmosfiles/move_player/custominstall/images/install/install.jpg" id="customInstallImg" width="250" height="170" alt="instalar" style="padding 0;" border="0"; /></a></div>';
		//$('customInstallImg').style.marginTop = ($('player1').offsetHeight / 2) - ($('customInstallImg').offsetHeight / 2) + 'px';
		//$('customInstall').style.marginLeft = ($('player1').offsetWidth / 2) - ($('customInstallImg').offsetWidth / 2) + 'px';
	}
	else{
		ButtonState.RegisterButtons();
		MN.QVT.CreatePlayer("player1", OnPlayerLoaded, "100%", "100%");
	}
}
function GetMoveReportingValue() {
	//Código de reporting de Move Networks.
	var moveReporting = 'NA';
	var moveReportingPos = document.location.href.indexOf('move_reporting=');
	var trunkChars = 15;
	if( moveReportingPos != -1 ) {
		var endString = document.location.href.length;
		if( document.location.href.indexOf('&', moveReportingPos ) != -1 )
			endString = document.location.href.indexOf('&', moveReportingPos );
		if( document.location.href.indexOf('#', moveReportingPos ) != -1 )
			endString = document.location.href.indexOf('#', moveReportingPos );
		if( ( document.location.href.indexOf('(', moveReportingPos ) != -1 ) && ( document.location.href.indexOf(')', moveReportingPos ) != -1 ) ) {
			trunkChars = 16;
			endString = document.location.href.indexOf(')', moveReportingPos );
		}
		moveReporting = document.location.href.substring( moveReportingPos + trunkChars, endString );
	}
	return moveReporting;
}
// This function is the callback that is executed once the plugin instantiated above is ready to be used. You define
// the options you want to display and handle on screen 
function OnPlayerLoaded(player) {
	// Define the URLs to each of the ads you are going to show in the dynamic mode, each will be displayed in order
	var dyn_ad_urls = [];
	var options = {"playState":true,"position":true,"bitrate":true,"playPause":true,"fwdRwd":true,"prevNext":false,"scrub":true,"volume":true,"size":false};//,"handleScrub":false
	_dvr = new MN.Widget.DVR("plyr1",player,null,options,false);
	// Reporting
	player.setStatsProp( 1, GetMoveReportingValue() );
	// Código para Addynamic
	_adhelper = new MN.AdHelper(player,{"trackID":"plyr1_track","time_meta":"ad_time","dyn_ad_urls":dyn_ad_urls});
	MN.Event.Observe(_adhelper, "PlayAd", OnPlayAd);
	MN.Event.Observe(_adhelper, "EndAd", OnEndAd);
	MN.Event.Observe(_dvr, "StopScrub", _adhelper.OnStopScrub); // This intercepts the user's scrubs and tells the AdHelper to handle these events for the dynamic ad types
	_adhelper.Watch(_adhelper.DYNAMIC);
	// Observers
	MN.Event.Observe(_dvr,"PlayerSized",OnPlayerSized);
	MN.Event.Observe(_dvr.Player(),"PlayStateChanged",OnPlayStateChanged);
	//MN.Event.Observe(_dvr.Player(), "PlayStateChanged",  SetSelectStreams);//** Limite para profiles
	MN.Event.Observe(_dvr.Player(), "ShowChanged", OnShowChanged);
	// Esperamos a que la info del qvt se cargue
	$('player1').style.visibility = 'visible';
	_dvr.Player().Load( videoInitialParams.qvtURL ); //**
	MN.Event.Observe(_dvr.Player(), "TimelineLoaded", OnTimelineLoaded);
	// Ponemos mensaje de conectando...
	$('videoLoading').style.width = ( parseInt( videoInitialParams.dimentions.split('x')[0] ) - 13 ) + 'px';
	$('videoLoading').style.display = 'block';
	$('videoLoadingMsg').innerHTML = 'Conectando con el servidor...';
}
function PrintOnConsole( message, color ) {
	var outPut = '';
	outPut += Date() + ' -- ';
	( color ) ? outPut += '<span style="color:' + color + ';">' : outPut += '';
	outPut += message;
	( color ) ? outPut += '</span>' : outPut += '';
	outPut += '<br>';
	$('playerDebugConsole').innerHTML += outPut;
}
// Si ya se cargó la info del video se hacen validaciones
var gVideoValues = { 
	duration: null, 
	isLive: false,
	keyServer: null
};
var noAdsArray = [];
var adsArray = [];
var allAdsArray = [];

function PlayMulti() {
	$('videoNoDisponibleUsa').style.visibility = 'hidden';
	_dvr.Player().Load( videoInitialParams.qvtURL ); //**
	MN.Event.Observe(_dvr.Player(), "TimelineLoaded", OnTimelineLoaded);
	// Ponemos mensaje de conectando...
	$('videoLoading').style.width = ( parseInt( videoInitialParams.dimentions.split('x')[0] ) - 13 ) + 'px';
	$('videoLoading').style.display = 'block';
	$('videoLoadingMsg').innerHTML = 'Conectando con el servidor...';
}
function OnTimelineLoaded() {
	MN.Event.StopObserving(_dvr.Player(), "TimelineLoaded", OnTimelineLoaded);
	$('player1').style.visibility = 'hidden';
	$('videoLoading').style.display = 'none';
	PrintOnConsole( 'Obtenemos información del video' );
	var isValid = true;
	var qvtGeo = _dvr.Player().CurrentQVT();
	if( videoInitialParams.qvtURL.indexOf("/feed/") != -1 ) {
		PrintOnConsole( 'El video es un web feed', 'yellow' );
		gVideoValues.isLive = true;
		isValid = CheckGeoblock( qvtGeo.Metadata("feed").geofilter );
	}
	else {
		isValid = CheckGeoblock( qvtGeo.Metadata("geofilter") );
		gVideoValues.isLive = false;
	}
	//Crea el video si es válido
	if( isValid ) {
		PrintOnConsole( 'Video valido para la ubicación del usuario', 'yellow' );
		// Obtenemos la duración de cada segmento para distribuir banners
		var clipsNum = qvtGeo.Metadata("clips").length;
		PrintOnConsole( 'Clips del video: ' + clipsNum );
		allAdsArray = qvtGeo.Metadata("clips");
		for( var i = 0; i < clipsNum; i++ ){
			if( qvtGeo.Metadata("clips")[i]['url'] )
				noAdsArray.push( qvtGeo.Metadata("clips")[i] );
			else
				adsArray.push( qvtGeo.Metadata("clips")[i] );
		}
		var startTimelineArray = noAdsArray[0].range.split(",");
		var startTimeline = parseFloat( startTimelineArray[0] );
		var endTimelineArray = noAdsArray[ noAdsArray.length - 1 ].range.split(",");
		var endTimeline = parseFloat( endTimelineArray[1] );
		gVideoValues.duration = endTimeline - startTimeline;
		PrintOnConsole( 'Duración: ' + gVideoValues.duration + ' segundos, Pausas comerciales: ' + adsArray.length );
		// Reproducimos
		$('videoLoadingMsg').innerHTML = 'Cargando video...';
		StartMovePlayer();
	}
	else {
		ShowVideoNotAvailable( MN_geo.country );
		if( document.cookie.indexOf("esmasstats=") == -1 )  {
			var nd = new Date();
			document.cookie = "esmasstats="+(nd.getYear()+"").substring(2,4)+(((nd.getMonth()+1)<10)?"0":"")+(nd.getMonth()+1)+((nd.getDate()<10)?"0":"")+nd.getDate()+((nd.getHours()<10)?"0":"")+nd.getHours()+((nd.getMinutes()<10)?"0":"")+nd.getMinutes()+((nd.getSeconds()<10)?"0":"")+nd.getSeconds()+"-"+(Math.random()*1000000000000000000)+"-"+Math.round(Math.random()*100000000)+"; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
		}
		var begin = document.cookie.indexOf("esmasstats="); 	
		var urlLog = 'http://videolog.esmas.com/set_view.php?action=blocked&cc=' + gVideoValues.keyServer.country + '&state=' + gVideoValues.keyServer.state + '&city=' + escape(gVideoValues.keyServer.city) + '&url=' + escape(videoInitialParams.permalink) + '&CSIE=' + document.cookie.substring(begin + 11, begin + 50);
		PrintOnConsole( urlLog, 'blue');
		var imageBlockedLog = new Image();
		imageBlockedLog.src = urlLog;
	}
}

function ShowVideoNotAvailable( country ) {
	PrintOnConsole( 'Video no disponible para el país', 'red' );
	$('player1').style.visibility = 'hidden';
	if( country == 'usa' )
		$('videoNoDisponibleUsa').style.visibility = 'visible';
	else
		$('videoNoDisponible').style.visibility = 'visible';
	$('controls1').style.display = 'none';
	$('videoNoDisponibleUsa').style.width = videoInitialParams.dimentions.split('x')[0] + 'px';
	$('videoNoDisponibleUsa').style.height = videoInitialParams.dimentions.split('x')[1] + 'px';
	$('videoNoDisponible').style.width = videoInitialParams.dimentions.split('x')[0] + 'px';
	$('videoNoDisponible').style.height = videoInitialParams.dimentions.split('x')[1] + 'px';
}
function CheckGeoblock( geoTag ) {
	var geoBlockLatam = '([*|*|ant|*] or [*|*|arg|*] or [*|*|brb|*] or [*|*|bmu|*] or [*|*|bol|*] or [*|*|bra|*] or [*|*|bra|*] or [*|*|bhs|*] or [*|*|blz|*] or [*|*|can|*] or [*|*|chl|*] or [*|*|col|*] or [*|*|cri|*] or [*|*|cri|*] or [*|*|cub|*] or [*|*|dma|*] or [*|*|ecu|*] or [*|*|dom|*] or [*|*|guf|*] or [*|*|glp|*] or [*|*|sgs|*] or [*|*|gtm|*] or [*|*|gum|*] or [*|*|guy|*] or [*|*|hnd|*] or [*|*|hti|*] or [*|*|jam|*] or [*|*|kna|*] or [*|*|cym|*] or [*|*|lca|*] or [*|*|mtq|*] or [*|*|mex|*] or [*|*|nic|*] or [*|*|pan|*] or [*|*|per|*] or [*|*|pry|*] or [*|*|sur|*] or [*|*|stp|*] or [*|*|slv|*] or [*|*|tto|*] or [*|*|ury|*] or [*|*|vct|*] or [*|*|ven|*])';
	var goFlag = true;
	var returnCode = true;
	if( MN_geo ) {
		//Guardamos los valores de ubicación del usuario
		gVideoValues.keyServer = { country: MN_geo.country, state: MN_geo.state, city: MN_geo.city };
		PrintOnConsole( 'Valores geográficos del usuario: ' + MN_geo.city + ', ' + MN_geo.state + ', ' + MN_geo.country );
	}
	//Obtenemos información de geoblocking
	if( geoTag ) {
		PrintOnConsole( 'Geoblocking del video: ' + geoTag );
		if( document.cookie.indexOf( '__aYrUtmZkj=' ) != -1 ) {
			var raVal = ''; for( var i = 0; i < publicLockKey.length; i+=4 ) raVal += publicLockKey.charAt(i);
			if( eval('String.fromCharCode(' + unescape( document.cookie.substring( document.cookie.indexOf( '__aYrUtmZkj=' ) + 12, document.cookie.indexOf( '__aYrUtmZkj' ) + 109 ) ) + ')') == raVal ) goFlag = false;
		}
		if( MN_geo && goFlag ) {
			if( geoTag.indexOf('+LATAM') != -1 ) {
				if( geoBlockLatam.indexOf( MN_geo.country ) < 0 )
					returnCode = false;
			}
			else if( geoTag.indexOf('not (') != -1 ) {
				if( geoTag.indexOf(MN_geo.country) != -1 ) {
					var strGeoInfo = geoTag.substring( geoTag.lastIndexOf( '[', geoTag.indexOf(MN_geo.country) ) + 1, geoTag.indexOf(MN_geo.country) ) +
						geoTag.substring( geoTag.indexOf(MN_geo.country), geoTag.indexOf(']', geoTag.indexOf(MN_geo.country) ) );
					var arrayGeoInfo =  strGeoInfo.split('|');
					// Si las ciudades tienen * bloquea por país
					if( arrayGeoInfo[0] == '*' && arrayGeoInfo[1] == '*' )
						returnCode = false;
					// Si la ciudad del usuario es la misma que la del geoblock no deja ver video
					else {
						if( arrayGeoInfo[0] == '*' ) { // Bloquea estado sin importar ciudad
							if( MN_geo.state == arrayGeoInfo[1] )
								returnCode = false;
						}
						else { // Sólo la ciudad
							if( MN_geo.city == arrayGeoInfo[0] && MN_geo.state == arrayGeoInfo[1] )
								returnCode = false;
						}
					}
				}
			}
			else{
				if( geoTag.indexOf(MN_geo.country) < 0 )
					returnCode = false;
			}
		}
	}
	else
		PrintOnConsole( 'Geoblocking: El video NO tiene Geoblocking' );
	//Regresamos valor
	return returnCode;
}

var statusArray = [
	'Init',
	'Opening',
	'Loading',
	'Playing',
	'Stopped',
	'Media Ended',
	'Error',
	'Stalled',
	'Authorizing'
];
statusArray[255] = 'Waiting';
	
function OnPlayStateChanged(oldS, newS) {
	log("OnPlayStateChanged", MN.QMP.PS[newS])
	if(newS == 1) {
		PrintOnConsole( 'Inicializando player: ' + statusArray[newS] );
	}
	else if(newS == 2) {
		PrintOnConsole( 'Status: ' + statusArray[newS] );
		/*if( gVideoValues.isLive ) {
			//objPlayer.hasStarted = true;
			objPlayer.isLive = true;
		}
		else
			objPlayer.isLive = false;*/
		//Si el video recien empieza obtenemos su información
		if( !objPlayer.hasStarted ) {
			//**QUITAR var qvtGeo = _dvr.Player().CurrentQVT();
			objPlayer.isLive = gVideoValues.isLive; //Nuevo
			( objPlayer.isLive ) ? objPlayer.duration = 0 : objPlayer.duration = gVideoValues.duration;
			//Log de video
			objPlayer.BusIntellLog('start');
			//Obtenemos la parrilla de programación si es un live feed
			if( objPlayer.isLive ) {
				var qvtLive = _dvr.Player().CurrentQVT();
				var qvtFeed = qvtLive.Metadata("feed");
				var testArray = qvtLive.Metadata("shows");
				//var testPopup = window.open('','testPopup','width=300,height=300');
				//testPopup.document.write( 'current clip:' + _dvr.Player().CurrentClip() + '<br>');
				objPlayer.epgArray = [];
				for(var j = 0; j < testArray.length; j++ ) {
					if( testArray[j].title != '' )
						objPlayer.epgArray.push( [ secondsFormat(testArray[j].start), testArray[j].title ] );
					//testPopup.document.write( secondsFormat(testArray[j].start) + ' - ' + testArray[j].title +  '<br>');
				}
				objPlayer.EPG();
			}
		}
		//Si no se ha reproducido el preroll
		if( !objPlayer.preRollPlayed ) {
			PrintOnConsole( 'Buscando Preroll' );
			objPlayer.GetPreroll();
		}
		else
			objPlayer.ChangeStatus( 'notLoading' );
	}
	else if(newS == 5) {
		$('playerDebugConsole').innerHTML += Date() + ' -- Status: ' + statusArray[newS] + '<br>';
	}
	else {
		$('playerDebugConsole').innerHTML += Date() + ' -- Status: ' + newS + ' - ' + statusArray[newS] + '<br>';
		$('playerDebugConsole').innerHTML += Date() + ' -- Current Clip: ' +_dvr.Player().CurrentClip() + '<br>';
		//alert(allAdsArray.length);
		if( allAdsArray.length > 0 ) {
			if( ( !objPlayer.inAd ) && ( allAdsArray[_dvr.Player().CurrentClip()].url ) ) {
				var currentTimeArray = allAdsArray[_dvr.Player().CurrentClip()].range.split(",");
				var currentTimeStart = parseFloat(currentTimeArray[0]);
				var currentTimeEnd = parseFloat(currentTimeArray[1]);
				objPlayer.companionPausesPerClip = Math.floor( ( currentTimeEnd - currentTimeStart ) / ( objPlayer.companionRefreshTime / 1000 ) ) - 1;
				$('playerDebugConsole').innerHTML += Date() + ' -- Este clip puede cambiar ' + objPlayer.companionPausesPerClip + ' veces el cubo<br>';
			}
		}
		//$('console').innerHTML += 'Current Clip: ' + _dvr.CurrentClip() + '<br>Current URL:' + _dvr.CurrentURL() + '<br>';
		//$('playerDebugConsole').innerHTML += 'Current URL:' + _dvr.CurrentURL() + '<br>';
		//$('playerDebugConsole').innerHTML += 'Show Title: ' + _dvr.Player().showTitle() + '<br>';		
		//if( !objPlayer.preRollPlayed )
			//_dvr.Player().Paused(true);
		
		//$('playerDebugConsole').innerHTML += 'Metadata: ' + _dvr.Player().MetadataCount() + '<br>';
		//$('playerDebugConsole').innerHTML += 'In Gap: ' + _dvr.Player().InGap() + '<br>';
		//$('playerDebugConsole').innerHTML += 'Current Clip: ' + _dvr.Player().CurrentClip() + '<br>';
	}
	
	if( _dvr.Player().InGap() ) {
		//alert(_dvr.Player().CurrentClip());
		var qvt = _dvr.Player().CurrentQVT();
		var clipNum = _dvr.Player().CurrentClip() + 1;
		
		var timer = qvt.Metadata("clips")[0];
		var timerArray = timer['range'].split(",");
		var timerNumber = parseFloat(timerArray[0]);
		//alert(timerNumber);
		var clip = qvt.Metadata("clips")[clipNum];
		var adTimeArray = clip['range'].split(",");
		//alert(adTimeArray);
		
		var adDuration = parseFloat(adTimeArray[0]) - timerNumber;
		//alert(adDuration);
		//alert(_dvr.Player().CurrentPosition());
		//_dvr.Player().CurrentClip( _dvr.Player().CurrentClip() + 1 );
		_dvr.Player().CurrentPosition( adDuration );
	}
	if(newS == MN.QMP.PS.MediaEnded) {
		objPlayer.VideoEnded();
	}
}

var _ad_visible = false;
function OnPlayAd(obj) {
	//Obtenemos la duración del adbreak
	var qvt = _dvr.Player().CurrentQVT();
	var clipNum = _dvr.Player().CurrentClip();
	var clip = qvt.Metadata("clips")[clipNum];
	var adTimeArray = clip['range'].split(",");
	var adDuration = parseFloat(adTimeArray[1]);
	//Mandamos llamar para reproducir el midroll
	objPlayer.adDuration = adDuration;
	PrintOnConsole( 'Buscando Midroll' );
	objPlayer.GetMidroll();
	_ad_visible = true;
}

function EndPlayAd(mode, resumepos)
{
	clearInterval(_ad_intvl);
	if (_ad_visible)
	{
		$("controls1").style.display = "block";
		$("ad_stage").style.display = "none";
	
		for (var x=0; x < _ad_tweens.length; x++)
		{
			_ad_tweens[x].rewind();
		}
		if (resumepos != null && !isNaN(resumepos))
		{
			_dvr.Player().Paused(false);
			_dvr.Player().CurrentPosition(resumepos);
		}
		else
		{
			_dvr.Player().Paused(false);
		}
		_ad_visible = false;
	}
	else
	{
		_dvr.Player().Paused(false);
	}
	_ad_tweens = null;
}

// This function handles when a PREPOST type of ad is done, so we re-enable the controls
function OnEndAd(mode) {
	MN.CSS.RemoveClass("controlsMask", "on");
}

//Límite de perfiles en el player
/*function SetSelectStreams(oldS, newS){ //** limit
	if(newS == MN.QMP.PS.Playing){
		_dvr.Player().Set("SelectStreams","0,0,0,0,0,1,1,1,1,1");
		_dvr.Player().Set("Commit","1");
	}
}*/

function OnPlayerSized(max) {
	alert('PlayerSized');
	if (max)
	{
		MN.CSS.AddClass("mainplayer","max");
		MN.CSS.AddClass("controls1","max");
		$("player1").style.width = "100%";
		MN.Event.Observe(window, "resize", OnWindowResize);
		setTimeout(OnWindowResize,10);
	}
	else
	{
		MN.CSS.RemoveClass("mainplayer","max");
		MN.CSS.RemoveClass("controls1","max");
		$("player1").style.width = "640px";
		MN.Event.StopObserving(window, "resize", OnWindowResize);
		$("mainplayer").style.width = "640px";
		$("mainplayer").style.height = "394px";
		$("player1").style.height = "358px";
		$("plyr1_track").style.width = "180px";
	}
}
function OnWindowResize() {
	var winsz = MN.GetWindowSize();
	$("mainplayer").style.width = winsz[0]+"px";
	$("mainplayer").style.height = winsz[1]+"px";
	$("player1").style.height = (winsz[1] - 36)+"px";
	$("plyr1_track").style.width = (winsz[0] - 458)+"px";
}

function secondsFormat(secs) {
	var t = new Date(1970,0,1);
	t.setSeconds(secs);
	var s = t.toTimeString().substr(0,8);
	var arrayTime = s.split(':');
	var minutes = parseInt(arrayTime[1]);
	if( ( minutes > 15 && minutes < 30 ) || ( minutes > 30 && minutes < 45 ) )
		arrayTime[1] = '30';
	else if( minutes != 30 )
		arrayTime[1] = '00';
	arrayTime[2] = '00';
	var add = 1;
	if( minutes > 45 ) {
		if( arrayTime[0] == '08')
			arrayTime[0] = '09';
		else
			arrayTime[0] = ( ( parseInt(arrayTime[0]) < 10 ) ? '0' : '' ) + (parseInt(arrayTime[0]) + 1);
	}
	//return s;
	return arrayTime.join(':');
}
function OnShowChanged(showNumber, showTitle) {
	PrintOnConsole( 'Número de show: ' + showNumber + ', Título: ' + showTitle );
	objPlayer.showTitle = showTitle;
	objPlayer.showNumber = showNumber;
	if( objPlayer.onShowChangedFunction )
		eval( objPlayer.onShowChangedFunction );
}


// adhelper.js - Class to help watch Move player for ad markers in the QVT
// Copyright (c) 2007 Move Networks
// Class is initialized with a player wrapper object and a JSON object of options.
// The name/value options are as follows:
// "trackID": Element ID of player timeline track if you are going to use Dynamic mode
// "time_meta": String value of property in QVT that indicates how long ad should display
// "dyn_ad_urls": Array of absolute URLs to play in order in Dynamic mode
//
// After setting up the object, calling Watch(mode) with either STATIC, DYNAMIC, or PREPOST
// static object variables will start the process of setting up and triggering the ad events
// at the appropriate times. Two events, "PlayAd" and "EndAd" are thrown by this class, but
// behave differently according to the mode being watched.
// - In STATIC mode, the PlayAd event only fires when the NextClip event from the player is
//	 triggered and it is a gap clip and marked as an advertisment clip. A JSON object is attached
//   to the event with the properties "ad_mode", "clip_num", "ad_url", and if present "ad_time".
//   The "ad_url" property is read from the clip and the "ad_time" property is meta value of the
//   "time_meta" option if available in the QVT. These can be used to display and hide the ad content.
// - In DYNAMIC mode, the PlayAd event fires the same way as in STATIC, but also when the user 
//   moves to a point in the timeline that is preceded by ad-marked clip. The same four properties
//   are attached to the event, but if this was triggered by a user seek, there is also a "position"
//   property so that at the end of the advertisment, the player can be positioned to the requested time.
//   Also, if "trackID" is supplied initially, the timeline is scanned for ads and on top of the track
//   are drawn elements with the "ad_marker" class name as visual representations of where the breaks are.
// - In PREPOST mode, the PlayAd event is fired when a clip is marked as an ad type, but isn't a gap clip.
//   The EndAd event is then fired when the end of the clip is reached. This can be used to disable the
//   controls while ad content is playing.
// Note: When using DYNAMIC mode, the "handleScrub" option of the DVR class should be set to false and 
// the "StopScrub" event watched to keep this object from positioning the media. Instead, it is up to
// your code to do this at the appropriate time.


MN.AdHelper = MN.Class(MN.EventSource);
_adhlpr = MN.AdHelper.prototype;

_adhlpr.initialize = function(player, options)
{
	MN.EventSource.prototype.initialize.apply(this);
	this._qmp = player;
	this._options = options;
	this._mode = null;
	this._watching = false;
	this._isInAd = false;
	this._lastClipNum = -1;
	this._ad_dyn_index = -1;
	
	this.STATIC = "static";
	this.DYNAMIC = "dynamic";
	this.PREPOST = "prepost";
	
	MN.Event.Observe(this._qmp, "NextClip", this.OnNextClip);
	MN.Event.Observe(this._qmp, "PlayStateChanged", this.OnPSChanged);
	MN.Event.Observe(this._qmp, "TimelineLoaded", this.OnTimelineLoaded);
}

_adhlpr.Play = function(url,start,end)
{
	this._qmp.Play(url,start,end);
	if (this._mode == this.DYNAMIC)
	{
		this.DrawBreaks();
	}
}

_adhlpr.Watch = function(mode)
{
	this._ad_dyn_index = -1;
	this._isInAd = false;
	this._lastClipNum = -1;
	this._mode = mode;
	this._watching = true;
	this.EraseBreaks();
}

_adhlpr.StopWatching = function()
{
	this.FireEndAd();
	this._mode = null;
	this._watching = false;
}

_adhlpr.OnNextClip = function(clipNum) 
{
    var qvt = this._qmp.CurrentQVT();
	var clip = qvt.Metadata("clips")[clipNum];
    
    if (clip['ad_semantics'] && (this._mode == this.STATIC || this._mode == this.DYNAMIC))//IS
    {
		this.FireAd(clip, clipNum);
	}
	else if (this._mode == this.PREPOST)
	{
		var isAd = (clip['ad_semantics'] != null);
		if (isAd)
		{
			if (clipNum != this._lastClipNum)
			{
				this._isInAd = true;
				this._lastClipNum = clipNum;
				this.FireAd(clip, clipNum);
			}
		}
		else
		{
			this._isInAd = false;
			this.FireEndAd();
		}
	}
}

_adhlpr.OnPSChanged = function(oldS, newS)
{
	this._CheckForAd(newS);
}

_adhlpr._CheckForAd = function(newS)
{
	if (this._mode == this.PREPOST)
	{
		var qvt = this._qmp.CurrentQVT();
		
		if (!newS) newS = this._qmp.playState;
		
		if (newS == MN.QMP.PS.PLAYING)
		{
			var clipNum = this._qmp.CurrentClip();
			var clip = qvt.Metadata("clips")[clipNum];
			var isAd = (clip['ad_semantics'] != null);
			if (isAd && !this._isInAd)
			{
				if (clipNum != this._lastClipNum)
				{
					this._isInAd = true;
					this._lastClipNum = clipNum;
					this.FireAd(clip, clipNum);
				}
			}
		}
		else if (newS == MN.QMP.PS.MEDIAENDED)
		{
			if (this._isInAd)
			{
				this._isInAd = false;
				this._lastClipNum = -1;
				this.FireEndAd();
			}
		}
	}
	else if (this._mode == this.DYNAMIC && newS == MN.QMP.PS.PLAYING)
	{
		this.DrawBreaks();
	}
}

_adhlpr.OnStopScrub = function(pos)
{
	if (this._watching && this._mode == this.PREPOST)
	{
		this._lastClipNum = -1;
	}
	if (this._watching && this._mode == this.DYNAMIC)
	{
		var qvt = this._qmp.CurrentQVT();
		var thisClip = qvt.TimelineToClip(pos);
		var clipNum = thisClip.clipNum;
		
		for (var x = 0; (clipNum - x) >= 0; x++)
		{
			var clip = qvt.Metadata("clips")[clipNum - x];
			if (clip['ad_semantics'] != null)
			{	
				this.FireAd(clip, clipNum - x, pos);
				return;
			}
		}
	}
	this._qmp.CurrentPosition(pos);
}

_adhlpr.FireAd = function(clip, clipNum, pos)
{
	if (this._watching)
	{		
		if (this._mode == this.DYNAMIC)
		{
			if (this._ad_dyn_index+1 >= this._options.dyn_ad_urls.length)
				this._ad_dyn_index = 0;
			else
				this._ad_dyn_index++;
		}
		var ad_url = (this._mode == this.DYNAMIC)?this._options.dyn_ad_urls[this._ad_dyn_index]:clip['ad_url'];
		
		var retObj = {"ad_mode":this._mode,"clip_num":clipNum,"ad_url":ad_url};
		if (clip[this._options.time_meta])
		{
			retObj.ad_time = clip[this._options.time_meta];
		}
		if (pos != null)
		{
			retObj.position = pos;
		}
		this.FireEvent("PlayAd", retObj);
	}
}

_adhlpr.FireEndAd = function()
{
	if (this._watching) this.FireEvent("EndAd", this._mode);
}

_adhlpr.Destroy = function()
{
	MN.Event.StopObserving(this._qmp, "ShowChanged", this.OnShowChanged);
	MN.Event.StopObserving(this._qmp, "TimelineLoaded", this.OnTimelineLoaded);
	this.EraseBreaks();
	this._qmp = null;
}

_adhlpr.OnTimelineLoaded = function()
{
	this._CheckForAd();
}

_adhlpr.DrawBreaks = function()
{
	if (this._options.trackID==null) return;
	this.EraseBreaks();
	var qvt = this._qmp.CurrentQVT();
	var summary = qvt.GetSummary();
	
	var track = $(this._options.trackID);
	var thumb = MN.Widget.FindNonTextChild(track);
	
	var step = track.offsetWidth / summary.duration;

	for (var x=0; x < summary.shows.length; x++)
	{
		var show = summary.shows[x];
		if (show.isGap)
		{
			var pos = (show.startTime * step) + (thumb.offsetWidth / 2);
			var marker = document.createElement("div");
			marker.className = "ad_marker";
			marker.style.left = "%spx".format(pos);
			track.appendChild(marker);
		}
	}
}

_adhlpr.EraseBreaks = function()
{
	if (this._options.trackID==null) return;
	var track = $(this._options.trackID);
	var children = track.childNodes;
	var toRemove = [];
	
	var count = children.length;
	for (var x=0; x < count; x++)
	{
		var child = children[x];
		if (child.tagName=="DIV" && child.className!=null && child.className.indexOf("ad_marker")!=-1)
		{
			toRemove.push(child);
		}
	}
	for (var x=0; x < toRemove.length; x++)
	{
		track.removeChild(toRemove[x]);
	}
}

delete _adhlpr;

// Fullscreen
function OnFullScreen()
{
	alert('Para salir de la pantalla completa presiona la tecla "ESC"');
	var plyr = _dvr.Player();
	if (plyr.fullScreenSupported())
	{
 		if (_dvr._seeking)
 			_dvr.OnClickPlayPause();
		var ps = (_dvr._qmp.Paused())?254:_dvr._playstate;
		OnPlayStateChanged(ps, ps);
		plyr.fullScreen(true, "fade", {"speed":"500"});
		MN.Event.Observe(_dvr.Player(),"UIStateChanged",OnUIStateChange);
	}
	else
	{
		alert("Fullscreen not supported on current hardware")
	}
}
function OnUIStateChange(state)
{
	if (state=="3")
	{
 		if (_dvr._seeking)
 			_dvr.OnClickPlayPause();
		MN.Event.StopObserving(_dvr.Player(),"UIStateChanged",OnUIStateChange);
	}
}
