function getCookieValue(varName) {
	if(!navigator.cookieEnabled)
		return null;
	if (document.cookie.length > 0) {
		if (document.cookie.indexOf(varName) != -1) { 
			(document.cookie.indexOf(";", document.cookie.indexOf(varName) + varName.length + 1) != -1) ? end = document.cookie.indexOf(";", document.cookie.indexOf(varName) + varName.length + 1) : end = document.cookie.length;
			return unescape(document.cookie.substring(document.cookie.indexOf(varName) + varName.length + 1, end));
		} 
	}
	return null;
}





// Regresa un objeto con el elemeto de la página solicitado en base a su ID
function GetObjectByID(objectID) {
	// Si el browser es NS 4 o menor
	if(document.layers)
		return document.layers[objectID];
	// Si el browser es IE 4 o +	
	else if(document.all)
		return eval('document.all.' + objectID);
	else
		return document.getElementById(objectID);
}


// Función para hacer scroll en la barra de clips
var movePixels = 150; 

function Move(dir) {
	var top = GetObjectByID("clip_strip").style.top;
	if( !top )
		top = "0px";
	if( !( top == "0px" && dir == 1 ) && !( top == (-1 * movePixels * (CatalogListing.categoryList[0].clipList.length - 1) ) + "px" && dir == -1 ) ) 
		top = ( parseInt( top.substring( 0, top.indexOf("px") ) ) + ( movePixels * dir ) ) + "px";
	GetObjectByID("clip_strip").style.top = top;	
}


var _dvr = 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.

//Preroll ads

var urlToPlay = null;
var retStart = -1;
var retStop = null;
var inAd = false;
var numOfAds = 0;
var liveSignal = 0;

function play(url, start, stop, numAds, bBack, goLive)
{
	//alert(numAds);
	inAd = false;
	//Decimos si corremos un ad -> live N
	if(goLive != null) {
		liveSignal = goLive;
		if( !(miniPlayerOn || fullPlayerOn) ) {
			GetObjectByID("controls1").style.display = "none";
			GetObjectByID("controls_ads").style.display = "block";
		}
	}
	
	$('nextGame').style.visibility = 'hidden';
	$('player1').style.visibility = 'visible';
	
	//$('nextGame').style.display = 'none';
	//$('player1').style.display = 'block';
	
	
	
	if(numAds == 0)
	{
		//GetObjectByID("controls1").style.display = "block";
		_dvr.Play(url, start, stop);
		return;
	}
	if(start != null)
		retStart = start;
	if(stop != null)
		retStop = stop;
	if(numAds != null)
		numOfAds = numAds;
	if(url != null)
		urlToPlay = url;
		
	(!bBack) ? PlayAd() : PlayAdBack();
}

function PlayAd()
{
	var length = cortinillas_list.length;
	var index = Math.floor(Math.random()*length);
	//alert(ad_list[index].id);
	var url = "http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/%s.qvt".format(cortinillas_list[index].id);
	
	log(url);
	inAd = true;
	numOfAds--;
	
	//Desactivamos controles
	if( !(miniPlayerOn || fullPlayerOn) ) {
		GetObjectByID("controls1").style.display = "none";
		GetObjectByID("controls_ads").style.display = "block";
	}
	_dvr.Play(url);
}
function PlayAdBack()
{
	var length = bBack_list.length;
	var index = Math.floor(Math.random()*length);
	//alert(ad_list[index].id);
	var url = "http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/%s.qvt".format(bBack_list[index].id);
	
	log(url);
	inAd = true;
	numOfAds--;
	
	//Desactivamos controles
	if( !(miniPlayerOn || fullPlayerOn) ) {
		GetObjectByID("controls1").style.display = "none";
		GetObjectByID("controls_ads").style.display = "block";
	}
	_dvr.Play(url);
}

function OnAdDone()
{
	log("OnAdDone", urlToPlay, numOfAds);
	if(numOfAds > 0)
	{
		PlayAd();
	}
	else
	{
		inAd = false;
		if(urlToPlay != null) {
			//Desactivamos controles
			if( !(miniPlayerOn || fullPlayerOn) ) {
				GetObjectByID("controls1").style.display = "block";
				GetObjectByID("controls_ads").style.display = "none";
			}
			_dvr.Play(urlToPlay, retStart, retStop);
		}
	}
}

function OnPlayStateChanged(oldS, newS)
{
	$('console').innerHTML += 'Id evento: ' + newS + ' ' + hoy.toGMTString() + '<br>';
	if(newS == 3) {
		//$('console').innerHTML += 'Current Clip: ' + _dvr.CurrentClip() + '<br>Current URL:' + _dvr.CurrentURL() + '<br>';
		$('console').innerHTML += 'Current URL:' + _dvr.CurrentURL() + '<br>';
		$('console').innerHTML += 'Show Title: ' + _dvr.Player().showTitle() + '<br>';		
		$('console').innerHTML += 'Metadata: ' + _dvr.Player().MetadataCount() + '<br>';
		$('console').innerHTML += 'In Gap: ' + _dvr.Player().InGap() + '<br>';
		$('console').innerHTML += 'Current Clip: ' + _dvr.Player().CurrentClip() + '<br>';
	}
	log("OnPlayStateChanged", MN.QMP.PS[newS])
	if(newS == MN.QMP.PS.MediaEnded)
	{
		if(inAd)
		{
			log("OnPlayStateChanged", "in ad");
			OnAdDone();
		}
		else
		{
			log("OnPlayStateChanged", "not in ad");
			
			//Desactivamos controles
			if( !(miniPlayerOn || fullPlayerOn) ) {
				GetObjectByID("controls1").style.display = "block";
				GetObjectByID("controls_ads").style.display = "none";
			}
			play(feed[liveSignal], -1, null,1,"bback"); //Descomentar al poner la señal
			if(liveSignal == 1)
				liveSignal = 0;
			//PlayAd();
		}
	}
}






//Funciones para armar player de move
function Init()
{
	if(!MN.QMPInstall.CanPlay()){
		$('player1').innerHTML = '<a id="customInstall" href="http://caposguanatosfut.webcindario.com/installplayer" onclick="window.open(this.getAttribute(\'href\'),\'popup\',\'width=650,height=600,status=yes,scrollbars=no,resizable=no,location=no,toolbar=no\');return false;"><img src="install.jpg" id="customInstallImg" width="395" height="224" alt="" 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%");
		//Staggering
		//MN.QVT.useServerClock = false;
		//MN.AJAX.GetLocalTimeAdjustSec('dummy.html', function(adjustSec){
   			//var RAND_OFFSET_MINUTES = 3;
   			//var randLiveOffset = Math.floor(Math.random() * (RAND_OFFSET_MINUTES * 60) );
   			//MN.QVT.clockAdjustSec = adjustSec - randLiveOffset;
   			//MN.QVT.CreatePlayer("player1", OnPlayerLoaded, "100%", "100%");
		//});
	}
	// Se cargan los supers
	//SupersPositioning();
	PrintClipsStart();
	//setTimeout(RotateSupers, (superRotationTime + 20) * 1000); //********* ACTIVAR para supers
	//setTimeout(RotateSupers, 5000); //********* ACTIVAR para supers
	//RefreshScore();
}
// 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)
{
	$("controls1").style.display = "block";
	var options = {"playState":true,"position":true,"bitrate":true,"playPause":true,"fwdRwd":true,"prevNext":false,"scrub":true,"volume":true,"size":true};
	
	//Definimos que señal se cargará al abrir el player
	urlToPlay = feed[2]; //Cambiar por 0 el día del partido
	//El primer video es un Ad
	inAd = true;
	//desactiva controles *** Descomentar si hay prerolls
	/*if( !(miniPlayerOn || fullPlayerOn) ) {
		GetObjectByID("controls1").style.display = "none"; 
		GetObjectByID("controls_ads").style.display = "block";
	}*/
	//Obtenemos random un ad
	var url = "http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/%s.qvt".format(ad_list[Math.floor( Math.random() * ad_list.length )].id);
	
	//comentar 3 lineas si esque hay un preroll al cargar el player **** 
	var url = feed[2];
	inAd = false;
	urlToPlay = null;
	
	_dvr = new MN.Widget.DVR("plyr1",player,url,options,true);
	MN.Event.Observe(_dvr.Player(), "PlayStateChanged",  OnPlayStateChanged);
	MN.Event.Observe(_dvr.Player(), "PlayStateChanged",  SetSelectStreams);//** limit
	MN.Event.Observe(_dvr.Player(), "ShowChanged",  OnShowChanged);
	MN.Event.Observe(_dvr,"PlayerSized",OnPlayerSized);
}

var hoy = new Date();
var showStarted = true;
var playingStill = false;

function OnShowChanged(showNumber, showTitle) {
	//alert('Cambio el show!');
	
	  $('nextGame').style.visibility='hidden';
	  $('player1').style.visibility='visible';
	
	//$('nextGame').style.display = 'none';
	//$('player1').style.display = 'block';
	
	//alert('ShowChanged: ' + showTitle);
	var hoy = new Date();
	$('console').innerHTML += 'Show Number: ' + showNumber + ' ' + hoy.toGMTString() + '<br>';
	$('console').innerHTML += 'Show Title: ' + showTitle + ' ' + hoy.toGMTString() + '<br>';
	//$('mn_show_title').innerHTML = '' + showTitle + '';
	if(showTitle != "") {
		//if( showTitle.indexOf('Futbol') != -1 ) {
			$('console').innerHTML += '<span style="color:red;">SE ENCONTRO UNA SEÑAL VALIDA</span><br>';
			
			$('player1').style.visibility='visible';
			$('nextGame').style.visibility='hidden';
			
			//$('player1').style.display = 'block';
			//$('nextGame').style.display = 'none';
			
			playingStill = false;
			/*if(!showStarted) {
				numOfAds = loadedAds;
				adIndex = 0;
				showStarted = true;
				$('console').innerHTML += 'Status:' + showStarted + '<br>';
				//alert(numOfAds);
				//_dvr.Player().Paused(true);
				play("", -1, null);
				
			}*/
		//}
	}
	else {
		//entra solo sí está en un espacio en blanco
		//alert ('consola');
		
		$('player1').style.visibility='hidden';
		$('nextGame').style.visibility='visible';
		
		//$('player1').style.display = 'none';
		//$('nextGame').style.display = 'block';
		
		$('console').innerHTML += 'Pon Imagen en lugar.....<br>';
		showStarted = false;
		playingStill = true;
		$('console').innerHTML += 'Status:' + showStarted + '<br>';
		if(fullPlayerOn)
			MaxPlayer();
	}
}

function SetSelectStreams(oldS, newS){ //** limit
	if(newS == MN.QMP.PS.Playing){
		_dvr.Player().Set("SelectStreams","0,0,0,0,0,0,0,1,1,1");//_dvr.Player().Set("SelectStreams","0,0,0,0,0,1,1,1,1,1");
		_dvr.Player().Set("Commit","1");
	}
}

function OnPlayerSized(max)
{
	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";
}



//Redimensión de player
var miniPlayerOn = false;
var fullPlayerOn = false;
var contentDivs = [
	'content_partido',
	'content_resumen', 
	'content_gef',
	'content_comments'
];

function MiniPlayer(which) {
	miniPlayerOn = true;
	for(i = 0; i < contentDivs.length; i++ ) {
		GetObjectByID(contentDivs[i]).style.display = "none";	
	}
	if( which == 'content_galerias' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('galeriaframe').src = "fotogalerias/america1.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('galeriaframe').src = "fotogalerias/chivas1.html";
	}
	else if( which == 'content_resultados' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('estadisticasframe').src = "http://www.esmas.com/sef/futbol/miclasico/estadisticasA.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('estadisticasframe').src = "http://www.esmas.com/sef/futbol/miclasico/estadisticasB.html";
	}
	else if( which == 'content_jugadores' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('jugadoresframe').src = "http://www.esmas.com/sef/futbol/miclasico/jugadoresA.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('jugadoresframe').src = "http://www.esmas.com/sef/futbol/miclasico/jugadoresB.html";
	}
	else if( which == 'content_movil' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('movilframe').src = "http://www.esmas.com/futbol/mi-clasico/el-clasico-de-clasicos-club-america-vs-chivas/movil/america.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('movilframe').src = "http://www.esmas.com/futbol/mi-clasico/el-clasico-de-clasicos-club-america-vs-chivas/movil/chivas.html";
	}
	else if( which == 'content_acciones' ) {
		// Comentar estas 4 líneas el día del partido
		//if( getCookieValue('team') == 'america' )	
		//	GetObjectByID('accionesframe').src = "http://mxm.esmas.com/mi-clasico/lineupA.php?id_partido=1748&equipo=america";
		//else if ( getCookieValue('team') == 'chivas' )
		//	GetObjectByID('accionesframe').src = "http://mxm.esmas.com/mi-clasico/lineupC.php?id_partido=1748&equipo=chivas";
		// Descomentar esta línea el día del partido
			GetObjectByID('accionesframe').src = "http://mxm.esmas.com/mi-clasico/minuto.php?id_partido=1748";
	}
	
	
	GetObjectByID(which).style.display = "block";	
	
	GetObjectByID("player1").style.width = "268px";	
	GetObjectByID("player1").style.maxWidth = "264px";
	GetObjectByID("player1").style.height = "200px";	
	GetObjectByID("player1").style.left = "106px";	
	GetObjectByID("player1").style.top = "63px";
	
	GetObjectByID("nextGame").style.width = "268px";	
	GetObjectByID("nextGame").style.maxWidth = "264px";
	GetObjectByID("nextGame").style.height = "200px";	
	GetObjectByID("nextGame").style.left = "106px";	
	GetObjectByID("nextGame").style.top = "63px";
	
	GetObjectByID("nextGameImg").style.width = "268px";	
	GetObjectByID("nextGameImg").style.height = "200px";	
	
	
	GetObjectByID("controls1").style.display = "none";
	GetObjectByID("controls_ads").style.display = "none";
	
	GetObjectByID("content").style.display = "block";
	GetObjectByID("regresar").style.display = "block";
	
	GetObjectByID("frame_brand").style.display = "none";
	//GetObjectByID("regresar").style.left = "107px";	
	//GetObjectByID("regresar").style.top = "261px";	
	
	//HideAllSupers(); //*** Cuando haya supers activar esto
}
function MaxPlayer() {
	miniPlayerOn = false;
	fullPlayerOn = false;
	
	GetObjectByID("content_partido").src = "about:blank";
			
	//Con patrocinio de Sony **********
	GetObjectByID("player1").style.width = "570px";	
	GetObjectByID("player1").style.maxWidth = "566px";	
	GetObjectByID("player1").style.height = "385px";	
	GetObjectByID("player1").style.left = "178px";	
	GetObjectByID("player1").style.top = "99px";	
	
	GetObjectByID("nextGame").style.width = "570px";	
	GetObjectByID("nextGame").style.maxWidth = "566px";	
	GetObjectByID("nextGame").style.height = "385px";	
	GetObjectByID("nextGame").style.left = "178px";	
	GetObjectByID("nextGame").style.top = "99px";
	
	GetObjectByID("nextGameImg").style.width = "570px";	
	GetObjectByID("nextGameImg").style.height = "385px";
	
	GetObjectByID("frame_brand").style.display = "block";
	
	//Sin patrocinio de Sony **********	 	
	/*GetObjectByID("player1").style.width = "644px";	
	GetObjectByID("player1").style.maxWidth = "640px";	
	GetObjectByID("player1").style.height = "458px";	
	GetObjectByID("player1").style.left = "142px";	
	GetObjectByID("player1").style.top = "63px";*/
	
	GetObjectByID("controls1").style.display = "block";
	/*if(!superPermanentView)
		GetObjectByID("controls1").style.top = "546px";	
	else
		GetObjectByID("controls1").style.top = "596px";*/
	GetObjectByID("controls1").style.top = "521px";
	GetObjectByID("controls1").style.left = "142px";	
	GetObjectByID("controls1").style.width = "644px";
			
	GetObjectByID("content").style.display = "none";
	GetObjectByID("regresar").style.display = "none";
	if(superPermanentView) //Si los supers son permanentes que se muestre el último
		GetObjectByID("super_" + currentSuper ).style.display = "block"; 
	GetObjectByID("companion_ad").style.display = "block";
	GetObjectByID("poll").style.display = "block";
}
function FullScreenPlayer() {
	if(!playingStill) {
		fullPlayerOn = true;
		GetObjectByID("player1").style.width = "945px";	
		GetObjectByID("player1").style.maxWidth = "941px";	
		GetObjectByID("player1").style.height = "613px";	
		GetObjectByID("player1").style.left = "1px";	
		GetObjectByID("player1").style.top = "1px";	
		GetObjectByID("controls1").style.display = "block";
		GetObjectByID("controls1").style.top = "615px";
		GetObjectByID("controls1").style.width = "945px";
		GetObjectByID("controls1").style.left = "1px";
		
		GetObjectByID("companion_ad").style.display = "none";
		GetObjectByID("poll").style.display = "none";
		HideAllSupers();
	}
}
function GoFull() {
	(fullPlayerOn) ? MaxPlayer() : FullScreenPlayer();
}
function Comunidades() {
	if( getCookieValue('team') == 'america' )	
		window.open('http://www.gyggs.com/grupo/america','_blank');
	else if ( getCookieValue('team') == 'chivas' )
		window.open('http://www.gyggs.com/grupo/laschivas','_blank');
}
	
// Funciones para rotar los supers
var currentSuper = 1;
var supersNumber = 1;
var superPermanentView = false;
var superShowingTime = 10; //Seconds
var superRotationTime = 240; //Seconds

function HideAllSupers() {
	for(i=0; i < supersNumber; i++)
		GetObjectByID("super_" + (i + 1) ).style.display = "none";
}

function HideSupers() {
	HideAllSupers();
	if( !(miniPlayerOn || fullPlayerOn) ) {
		GetObjectByID("player1").style.height = "385px";
		GetObjectByID("frame_brand_bottom").style.top = "1px";
	}
}

function RotateSupers() {
	//Si el player está en mini o full no cambiar los banners
	if( !(miniPlayerOn || fullPlayerOn) ) {
		HideAllSupers();
		if( !superPermanentView ){
			GetObjectByID("player1").style.height = "335px";
			GetObjectByID("frame_brand_bottom").style.top = "-50px";
			var supersTimer = setTimeout(HideSupers, superShowingTime * 1000);
		}
		GetObjectByID("super_" + currentSuper ).style.display = "block"; 
		currentSuper ++;
		if( currentSuper > supersNumber )
			currentSuper = 1;
	}
	var supersRotationTimer = setTimeout(RotateSupers, superRotationTime * 1000);
}

function SupersPositioning() {
	if(superPermanentView) {
		GetObjectByID("player1").style.height = "408px";
		for(i=0; i < supersNumber; i++)
			GetObjectByID("super_" + (i + 1) ).style.top = "471px";
		//GetObjectByID("controls1").style.top = "521px";	
	}
}

/*window.captureEvents(Event.KEYPRESS);
window.onkeypress = pressed;

function pressed(e) {
  alert("Key pressed! ASCII-value: " + e.which);
}*/

function getCookieValue(varName) {
	if(!navigator.cookieEnabled)
		return null;
	if (document.cookie.length > 0) {
		if (document.cookie.indexOf(varName) != -1) { 
			(document.cookie.indexOf(";", document.cookie.indexOf(varName) + varName.length + 1) != -1) ? end = document.cookie.indexOf(";", document.cookie.indexOf(varName) + varName.length + 1) : end = document.cookie.length;
			return unescape(document.cookie.substring(document.cookie.indexOf(varName) + varName.length + 1, end));
		} 
	}
	return null;
}

// Código para controlar el round robin del sponsored
/*var randomNumber = Math.floor( Math.random() * 2 );
if( getCookieValue('brand') ) {
	if( getCookieValue('brand') == 'banamex' ) {
		randomNumber = 1
		document.cookie = "brand=telcel; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
	}
	else if( getCookieValue('brand') == 'telcel' ) {
		randomNumber = 0
		document.cookie = "brand=banamex; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
	}
	else
		randomNumber = 0
}
else {
	if(randomNumber == 0)
		document.cookie = "brand=banamex; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
	else
		document.cookie = "brand=telcel; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
}*/

//Código para controlar los fondos de los patrocinadores
var sponsorsThemesArray = [
	//Background, Botón
	["xboxBG.jpg", "SenalBotxBox.png", "#000000", "headxbox.jpg", "#FFFFFF"],
	["xboxBG.jpg", "SenalBotxBox.png", "#000000", "headxbox.jpg", "#FFFFFF"]
	//["cocaBG.jpg", "SenalBot_coca.png", "#FFFFFF", "headcoca.jpg", "#000000"]
];
var sponsorRandomNumber = Math.floor( Math.random() * sponsorsThemesArray.length );
if( getCookieValue('sponsorIndex') ) {
	//alert("Cookie:"+getCookieValue('sponsorIndex'));
	if( parseInt( getCookieValue('sponsorIndex') ) == (sponsorsThemesArray.length - 1) )
		sponsorRandomNumber = 0;
	else
		sponsorRandomNumber = parseInt( getCookieValue('sponsorIndex') ) + 1
	document.cookie = "sponsorIndex=" + sponsorRandomNumber + "; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
}
else {
	//alert('no cookie');
	document.cookie = "sponsorIndex=" + sponsorRandomNumber + "; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
}
//alert("Index:" + sponsorRandomNumber);
document.write('<style type="text/css">');
document.write('BODY { background-image: url(images/skins/' + sponsorsThemesArray[sponsorRandomNumber][0] + '); }');
document.write('#channels UL LI { background-image: url(images/skins/' + sponsorsThemesArray[sponsorRandomNumber][1] + '); }');
document.write('#channels UL LI A { color: ' + sponsorsThemesArray[sponsorRandomNumber][2] + '}');
document.write('#options LI A { color: ' + sponsorsThemesArray[sponsorRandomNumber][2] + '}');
document.write('#content DIV UL.header { background-image: url(images/skins/' + sponsorsThemesArray[sponsorRandomNumber][3] + '); }');
document.write('#content DIV LI.header_txt { color: ' + sponsorsThemesArray[sponsorRandomNumber][2] + '}');
document.write('#content DIV LI.imagen h2 { color: ' + sponsorsThemesArray[sponsorRandomNumber][2] + '}');
document.write('#content DIV { background-color: ' + sponsorsThemesArray[sponsorRandomNumber][4] + '}');
document.write('</style>');

/* Validamos el equipo del usuario y cambiamos el fondo*/
/*if( getCookieValue('team') == 'america')	
	document.write('<style type="text/css">	BODY { background-image: url(images/skins/xboxBG.jpg); } </style>');
else if ( getCookieValue('team') == 'chivas' )
	document.write('<style type="text/css">	BODY { background-image: url(images/skins/xboxBG.jpg); } </style>');*/

/* 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 = "";
var xmlHttpError = "";
/********************************************************************************************************************
 * 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 getHttpRequest(action, execute, domObject, message) {
	
	var oXmlHttp = createXMLHttp();
	//oXmlHttp.setRequestHeader("Content-type", "text/html; charset=ISO-8859-1");
	//oXmlHttp.setRequestHeader("Cache-Control", "no-cache"); 
	oXmlHttp.open("get", action, true);	
	oXmlHttp.onreadystatechange = function () {
		if ( oXmlHttp.readyState == 4 ) {
			if( oXmlHttp.status == 200 )
				xmlHttpResult = oXmlHttp.responseText;
			else {	
				xmlHttpResult = "*** ERROR *** <br/><a href='javascript:alert(xmlHttpError);'>Ver detalle</a>";
				xmlHttpError = "Error ID : " + oXmlHttp.status + "\nDescripción : " + oXmlHttp.responseText;
			}
			if( domObject != '' ) {
				GetObjectByID(domObject).innerHTML = oXmlHttp.responseText;
			}
			if( execute != '' )
				eval(execute);
		}
	};
	oXmlHttp.send(null);
}

function PrintClipsAjax() {
	var JSONObject = eval('(' + xmlHttpResult + ')');
	var thumbnailImg = '';
	var claseHead = null;
	
	//GetObjectByID("clip_strip").innerHTML = '';
	GetObjectByID("content_partido").innerHTML = ''; 
	
	if( getCookieValue('team') == 'america' )	
		claseHead = 'header';
	else if ( getCookieValue('team') == 'chivas' )
		claseHead = 'header'; //'headerchivas' antes!
	claseHead = 'header';

	var header01 = '<ul class="' + claseHead + '"><li class="header_txt">';
	var header02 = '</li><li><a href="javascript:void(null);" onclick="parent.MaxPlayer();"><img src="http://i.esmas.com/img/univ/spacer.gif" height="20" width="60" border="0" style="float:right;"/></a></li></ul><ul class="thumb">';
	
	//Armamos los headers de cada sección de contenido
	var partidoTD = header01 + 'Partidos completos pasados' + header02;
	var resumenTD = header01 + 'Resúmenes' + header02;
	var gefTD = header01 + 'Gol, error y figura' + header02;
	//var facundo = header01 + 'Más de Facundo' + header02;
	
	for(i=0; i < CatalogListing.categoryList[0].clipList.length; i++) {
		// Validamos que tenga thumbnail
		if( CatalogListing.categoryList[0].clipList[i].thumbnail )
			thumbnailImg = CatalogListing.categoryList[0].clipList[i].thumbnail.thumb_url;
		else
			thumbnailImg = '';
		
		//Llenamos el carrusel de clips de la izq
		//GetObjectByID("clip_strip").innerHTML += 
			'<li><a href="javascript:play(\'http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/' + CatalogListing.categoryList[0].clipList[i].id + '.qvt\',0,null,1);">' +
			'<img src="' + thumbnailImg + '"></a>' +
			'<h5>' + CatalogListing.categoryList[0].clipList[i].name + '</h5>';
			
		//Validar si tiene campo de cat que imprima en los divs tematicos	
		if(CatalogListing.categoryList[0].clipList[i].metadata) {
			currentClip = 
				'<li class="imagen">' +
				'<a href="javascript:play(\'http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/' + CatalogListing.categoryList[0].clipList[i].id + '.qvt\',0,null,1);">' +
				'<img src="' + thumbnailImg + '" class="thumbnail" height="60" width="80"></a>' +
				'<h2>' + CatalogListing.categoryList[0].clipList[i].name + '</h2>';
			//Partidos completos
			if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "partido")
				partidoTD += currentClip;
			//Resúmenes
			else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "resumen")
				resumenTD += currentClip;
			//Gol error y figura
			else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "gef")
				gefTD += currentClip;
			//Facundo
			//else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "facundo")
				//facundo += currentClip;	
		}
	}
	partidoTD += '</ul>';
	resumenTD += '</ul>';
	gefTD += '</ul>';
	//facundo += '&nbsp;&nbsp;<a href="http://www.facundo.com.mx" target="_blank">Ve más de Facundo www.facundo.com.mx</a></ul>';
	
	GetObjectByID("content_partido").innerHTML = partidoTD;
	GetObjectByID("content_resumen").innerHTML = resumenTD;
	GetObjectByID("content_gef").innerHTML = gefTD;
	//GetObjectByID("content_facundo").innerHTML = facundo;
}

var loadingMessage = '<h4>Actualizando...</h4><h4><img src="img/ajax-loader.gif"></h4>';

// Funciones para recargar los clips
function PrintClipsStart() {
	//GetObjectByID("clip_strip").innerHTML = loadingMessage;
	GetObjectByID("content_partido").innerHTML = loadingMessage;
	GetObjectByID("content_resumen").innerHTML = loadingMessage;
	GetObjectByID("content_gef").innerHTML = loadingMessage;
	//GetObjectByID("content_facundo").innerHTML = loadingMessage;
	setTimeout(PrintClips, 1000);
}
var clipCounter = 1000;//Math.random();
var scoreCounter = 0;//Math.random();
var ajaxLoaderImg = new Image();
ajaxLoaderImg.src = "img/ajax-loader.gif";


function PrintClips() {
	//Llama el archivo de clips
	getHttpRequest(
		'js/listing.js?' + clipCounter,
		'PrintClipsAjax()',
		'',
		''
	);
	clipCounter ++;
	//setTimeout(PrintClipsStart, 300000); Si los clips estarán cargandose cada x tiempo
}
// Actualizar el marcador y el minuto
function RefreshScore() {
	//Llama el archivo de score http://mxm.esmas.com/mi-clasico/marcador.php?id_partido=1748
	//'http://mxm.esmas.com/mi-clasico/marcador.php?id_partido=1748&min=' + scoreCounter,
	getHttpRequest(
		'js/score.js?' + scoreCounter,
		'PrintScoreAjax()',
		'',
		''
	);
	//setTimeout(RefreshScore, 60000); // Para actualizar el score en linea
}
function PrintScoreAjax() {
	var values = xmlHttpResult.split(",");
	GetObjectByID("options_score").innerHTML = values[0];
	GetObjectByID("options_minute").innerHTML = '<!--Minuto: -->' + values[1];
	scoreCounter = parseInt(values[1]);
}


function writeSmallDate(){
	monthNames = new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre");
	theDate = new Date();
	document.write( theDate.getDate() + " de " + monthNames[theDate.getMonth()]   + " de "  + theDate.getFullYear());
}

//if( (document.location.href.indexOf('zeus2.esmas.com.mx') != -1) || (document.location.href.indexOf('toga04.esmas.com.mx') != -1) ) {
	//document.cookie = "team=chivas; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/;";
//}
// Si no está logueado que lo mande a registro
//if( !getCookieValue('team') )
	//document.location = 'registro.html';