// 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;	
}

//Redimensión de player
var miniPlayerOn = false;
var fullPlayerOn = false;
var contentDivs = [
	'content_acciones',
	'content_resultados',
	'content_galerias',
	'content_comments',
	'content_tutoma',
	'content_jpartido',   
	'content_phantomhd',
	'content_seleccion',
	'content_capsulascoca',
	'content_previo'	 
];
var accionesWasLoaded = false;
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 = "http://www.televisadeportes.com/eventos/mexico-vs-estados-unidos/fotogalerias/fgal_01.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.televisadeportes.com/eventos/mexico-vs-estados-unidos/estadisticas_clasico/mexico-costaRica/index.html";
		//else if ( getCookieValue('team') == 'chivas' )
			//GetObjectByID('estadisticasframe').src = "estadisticas_clasico/estadisticasB.html";
	}
	/*else if( which == 'content_jugadores' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('jugadoresframe').src = "estadisticas_clasico/jugadoresA.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('jugadoresframe').src = "estadisticas_clasico/jugadoresB.html";
	}*/
	/*else if( which == 'content_movil' ) {
		if( getCookieValue('team') == 'america' )	
			GetObjectByID('movilframe').src = "movil/america.html";
		else if ( getCookieValue('team') == 'chivas' )
			GetObjectByID('movilframe').src = "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
		if(!accionesWasLoaded) {
			GetObjectByID('accionesframe').src = "http://mxm2.televisadeportes.com/futbol/widgets/comentariosEspecial_iframe.php?id_torneo=81&id_partido=2974";
			accionesWasLoaded = true;
		}
	}
	GetObjectByID(which).style.display = "block";	
	objPlayer.SetSize("263x200");
	GetObjectByID("move_player").style.width = "263px";	
	GetObjectByID("move_player").style.maxWidth = "261px";
	GetObjectByID("move_player").style.height = "200px";	
	GetObjectByID("move_player").style.left = "195px";//123px	
	GetObjectByID("move_player").style.top = "86px"; //102px
	
	GetObjectByID("regresar").style.display = "block";
	GetObjectByID("regresar").style.left = "195px";//123px	
	GetObjectByID("regresar").style.top = "285px";//323px
	
	GetObjectByID("playerContent").style.display = "block";
	GetObjectByID("videoControls").style.display = "none";
	
	//GetObjectByID("nextGame").style.width = "263px";	
	//GetObjectByID("nextGame").style.maxWidth = "258px";
	//GetObjectByID("nextGame").style.height = "200px";	
	//GetObjectByID("nextGame").style.left = "195px";//119px	
	//GetObjectByID("nextGame").style.top = "86px";//102px
	
	//GetObjectByID("nextGameImg").style.width = "263px"; //268px	
	//GetObjectByID("nextGameImg").style.height = "200px";	
	//GetObjectByID("controls_ads").style.display = "none";
	
	
	
	
	//HideAllSupers(); //*** Cuando haya supers activar esto
}
function MaxPlayer() {
	miniPlayerOn = false;
	fullPlayerOn = false;
	
	GetObjectByID("galeriaframe").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 **********	 
	objPlayer.SetSize("601x465");	//("644x458")
	GetObjectByID("move_player").style.width = "601px"; //644px	
	GetObjectByID("move_player").style.maxWidth = "597px"; //640px	
	GetObjectByID("move_player").style.height = "465px";//458px	
	GetObjectByID("move_player").style.left = "208px";//142px	
	GetObjectByID("move_player").style.top = "86px"; //102px
	GetObjectByID("playerContent").style.display = "none";
	GetObjectByID("regresar").style.display = "none";
	GetObjectByID("videoControls").style.display = "block";
	
	//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() {
	fullPlayerOn = true;
	objPlayer.SetSize("945x613");
	GetObjectByID("move_player").style.width = "945px";	
	GetObjectByID("move_player").style.maxWidth = "941px";	
	GetObjectByID("move_player").style.height = "613px";	
	GetObjectByID("move_player").style.left = "1px";	
	GetObjectByID("move_player").style.top = "1px";	
	//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=/;";
}*/
/* 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/player-skin-back.jpg); } </style>');
//else if ( getCookieValue('team') == 'chivas' )
	//document.write('<style type="text/css">	BODY { background-image: url(images/skins/player-skin-back.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);
}

var loadingMessage = '<h4>Actualizando...</h4><h4><img src="http://i2.esmas.com/deportes30/eventos/mexico-vs-estados-unidos/img/ajax-loader.gif"></h4>';

// Funciones para recargar lso clips
var clipsInterval = null;
function PrintClipsStart() {
	GetObjectByID("clip_strip").innerHTML = loadingMessage;
	GetObjectByID("content_jpartido").innerHTML = loadingMessage;
	GetObjectByID("content_phantomhd").innerHTML = loadingMessage;
	GetObjectByID("content_seleccion").innerHTML = loadingMessage;
	GetObjectByID("content_capsulascoca").innerHTML = loadingMessage;
	setTimeout(PrintClips, 1000);
	clipsInterval = setInterval('PrintClips()', 300000);
}
var clipCounter = 3000;//Math.random();
var scoreCounter = 0;//Math.random();
var ajaxLoaderImg = new Image();
ajaxLoaderImg.src = "http://i2.esmas.com/deportes30/eventos/mexico-vs-estados-unidos/img/ajax-loader.gif";

function PrintClips() {
	//Llama el archivo de clips
	getHttpRequest(
		'js/listing.js?' + clipCounter,
		'PrintClipsAjax()',
		'',
		''
	);
	clipCounter ++;
	//alert(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.televisadeportes.com/miclasico/marcador.php?id_partido=2102&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 PrintClipsAjax() {
	var JSONObject = eval('(' + xmlHttpResult + ')');
	var thumbnailImg = '';
	var claseHead = null;
	
	GetObjectByID("clip_strip").innerHTML = '';
	GetObjectByID("content_jpartido").innerHTML = '';
	GetObjectByID("content_phantomhd").innerHTML = ''; 
	GetObjectByID("content_seleccion").innerHTML = '';
	GetObjectByID("content_capsulascoca").innerHTML = '';
	
	//if( getCookieValue('team') == 'america' )	
		claseHead = 'header';
	//else if ( getCookieValue('team') == 'chivas' )
		//claseHead = 'headerchivas';

	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="contenedor"><ul class="thumb">';
	
	//Armamos los headers de cada sección de contenido
	var JugPart = header01 + 'Jugadas del partido' + header02;
	var phantomHD = header01 + 'Tecnolog&iacute;a TD' + header02;
	var selecNal = header01 + 'Partidos Selecci&oacute;n Nacional' + header02;
	var capsCoca = header01 + 'C&aacute;psulas Coca Cola' + 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>';
			//jugadas del partido
			if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "jugpart")
				JugPart += currentClip;
			//PhantomHD
			else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "phantomhd")
				phantomHD += currentClip;
			//Partidos Seleccion Nacional
			else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "selecnal")
				selecNal += currentClip;
			//Capsulas Coca Cola
			else if(CatalogListing.categoryList[0].clipList[i].metadata.cat == "capscoca")
				capsCoca += currentClip;
		}
	}
	phantomHD += '</ul>';
	selecNal += '</ul>';
	capsCoca += '</ul>';
	
	GetObjectByID("content_jpartido").innerHTML = JugPart;
	GetObjectByID("content_phantomhd").innerHTML = phantomHD;
	GetObjectByID("content_seleccion").innerHTML = selecNal;
	GetObjectByID("content_capsulascoca").innerHTML = capsCoca;
}

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';
	
//-- Para generar cookie de los usuarios en Smarty

function SmrtPrflr() {
	//0:Id, 1:Browser, 2:Genero, 3:Edad, 6:Token, 7:Origin, 8:Email
	this.profile = null;
	this.profileArray = null;
	this.profileId = null;
	this.userOption = null;
	this.userOptionIndex = 0;
	this.surveyIndex = null;
	//this.surveysData = objSurveysData;
	
	this.GetUserAgent = function() {
		var arrayClients = [['Chrome', 'CH'], ['OmniWeb', 'OM'], ['Apple', 'SA'], ['Firefox', 'FF'], ['MSIE', 'IE'], ['Netscape', 'NE'] ];
		for( var i = 0; i < arrayClients.length; i++) {
			if( navigator.userAgent.indexOf( arrayClients[i][0] ) != -1 )
				return arrayClients[i][1];
		}
		return 'NA';
	}
	this.Log = function( title, value ) {
		if( $('console') )
			$('console').innerHTML += title + ': ' + value + '<br>';
		else
			return false;
		return true;
	}
	this.ProfileGetValue = function( label ) { 
		for(var i = 0; i < this.profileArray.length; i++) {
			if( this.profileArray[i].indexOf(label+':') != -1 )
				return this.profileArray[i].substring( this.profileArray[i].indexOf(':') + 1, this.profileArray[i].length );
		}
		return false;
	}
	this.ProfileAddValue = function( label, value ) { 
		for(var i = 0; i < this.profileArray.length; i++) {
			if( this.profileArray[i].indexOf(label+':') != -1 ) {
				this.profileArray[i] = label + ':' + value;
				return true;
			}
		}
		this.profileArray.push( label + ':' + value );
		return true;
	}
	this.getCookie = function( value ) { 
		if ( document.cookie.length > 0 ) { 
			if( document.cookie.indexOf( value ) != -1 ) {
				var begin = document.cookie.indexOf( value ) + value.length + 1;
				var end = 0; 
				(document.cookie.indexOf(";", begin) != -1)? end = document.cookie.indexOf(";", begin) : end = document.cookie.length;
				return unescape(document.cookie.substring(begin, end));
			} 
		}
		return false;
	}
	this.SaveCookie = function() {
		document.cookie = "SmrtPrflr=" + this.profileArray.join(',') + "; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/";
	}
	this.ServerLog = function() {
		this.logImage = null;
		this.logImage = new Image();
		this.logImage.src = 'http://stats.esmas.com/stats/collectornew.cgi?-|-|nmagnum|||' + this.profileArray.join(',') + '||||';
		//alert('http://stats.esmas.com/stats/collectornew.cgi?-|-|nmagnum|||' + urlString + '||||');
		this.Log( 'ServerLog', this.profileArray.join(',') )
		return true;
	}
	var newUserAdded = true;
	//alert(this.getCookie('esmasstats'));
	if( !this.getCookie('SmrtPrflr') )
		document.cookie = "SmrtPrflr=0:" + this.getCookie('esmasstats') + "; expires=Fri, 31 Jan 2020 23:59:59 GMT; path=/";
	else
		newUserAdded = false;
	
	this.profile = this.getCookie('SmrtPrflr');
	this.profileArray = this.profile.split(',');
	this.profileId = this.ProfileGetValue('0');
	
	if( newUserAdded ) {
		//if( !this.ProfileGetValue('1') )
		this.ProfileAddValue( '1', this.GetUserAgent() );
		this.ProfileAddValue( '7', 'MUSA' );
		if( this.getCookie('token') )
			this.ProfileAddValue( '6', this.getCookie('token') );
		this.SaveCookie();
	}
	else {
		if( !(this.ProfileGetValue('6')) && (this.getCookie('token')) ) {
			this.ProfileAddValue( '6', this.getCookie('token') );
			this.SaveCookie();
			//this.ServerLog( '0:' + this.profileId + ',6:' + this.ProfileGetValue('6') );
		}
		//alert('Ya existe el usuario');
	}
	
	//this.Log( 'Id', this.profileId ); 
	//this.Log( 'Browser ', this.GetUserAgent() ); 
	//this.Log( 'Genero ', this.ProfileGetValue('2') ); 
	//this.Log( 'Fumas ', this.ProfileGetValue('5') );
	//this.Log( 'Estado civil ', this.ProfileGetValue('3') );
	//this.Log( 'Tiene automóvil ', this.ProfileGetValue('4') );
	//this.Log( 'token ', this.ProfileGetValue('6') );
	
	//Generamos la encuesta
}
var objProfiler = null;