var wd;
	
	function cortaCadena(cadena,maximo){
		if(cadena.length > maximo){
			return cadena.substring(0,maximo);
		}
		else{
			return cadena;
		}
	}
	
	function iniciar(tipoWidget){
		wd = new Widget(tipoWidget);
		// esto hacia que a veces se cargara 2 veces wd.cargarPartidos();
		var pe = new PeriodicalExecuter(cargarPartidos,$F('tiempoRefrescoHid') / 6);
	}
	
	function cargarPartidos(){
		wd.cargarPartidos();
	}

var Widget = Class.create({
	gmt: null,
	maxPartidosMostrar: null,
	tipoWidget: null,

	deporte: null,
	nombreLiga: null,
	jornada: null,
	parametrosBusqueda: null,
	listaPartidos: [],

	listaDias: [],
	partidosClasificados: [],
	inicialSN: false,
	destinoLink: null,
	destinoClasif: null,
	ligasBasket: null,
	pantalla: 0,
	
	initialize: function(tipoWidget){
		var d = new Date();
		this.gmt = d.getTimezoneOffset();

		this.tipoWidget = tipoWidget;
		this.deporte = 'futbol';
		this.nombreLiga = 'PRIMERA';
		this.destinoLink = 'http://www.marcadoresonline.com/';
		this.destinoClasif = 'http://www.marcadoresonline.com/clasificacion/?';
		if($('ligaHid').value != ''){
			this.nombreLiga = $('ligaHid').value;
		}
		this.maxPartidosMostrar = 11;
		this.ligasBasket = ['ACB','NBA','BBL','LNB','LEGA A','GRE-BK','ISR-BK','TUR-BK','RUS-BK', 'EUROLIGA'];
		if(this.esLigaBasket(this.nombreLiga)){
			this.verDeporte('baloncesto');
		}
		else if(this.nombreLiga != 'PRIMERA'){
			this.verLiga(this.nombreLiga);
		}
		else{
			this.cargarPartidos();
		}
	},
	
	esLigaBasket: function(liga){
		for(var i=0; i < this.ligasBasket.length; i++){
			if(liga == this.ligasBasket[i])		return true;
		}
		return false;
	},
	
	// funciones de control
	verDeporte: function(deporte){
		var divFutbol = 'submenu';
		var divBaloncesto = 'submenuBsk';
		var divBotonFutbol = 'btFutbol';
		var divBotonBsk = 'btBsk';
		var tiposBotones = ['','Uno','Dos','Tres','Cuatro'];
		var tiposSubmenus = ['','Uno','Dos','Tres','Cuatro'];
		
		this.deporte = deporte;
		switch(this.deporte){
			case 'futbol':
				this.destinoLink = 'http://www.marcadoresonline.com/';
				this.destinoClasif = 'http://www.marcadoresonline.com/clasificacion/?';
				$('submenu' + tiposSubmenus[this.tipoWidget]).setStyle({'display' : 'block'});
				$(divBaloncesto + tiposSubmenus[this.tipoWidget]).setStyle({'display': 'none'});
				$(divBotonFutbol).className = 'btFutbol' + tiposBotones[this.tipoWidget] +  'Activo';
				$(divBotonBsk).className = 'btBsk' + tiposBotones[this.tipoWidget];
				this.verLiga('PRIMERA');
				break;
			case 'baloncesto':
				this.destinoLink = 'http://www.marcadoresonline.com/baloncesto/';
				this.destinoClasif = 'http://www.marcadoresonline.com/clasificacion/?deporte=3&';
				$('submenu' + tiposSubmenus[this.tipoWidget]).setStyle({'display' : 'none'});
				$(divBaloncesto + tiposSubmenus[this.tipoWidget]).setStyle({'display': 'block'});
				$(divBotonFutbol).className = 'btFutbol' + tiposBotones[this.tipoWidget];
				$(divBotonBsk).className = 'btBsk' + tiposBotones[this.tipoWidget] + 'Activo';
				if(!this.esLigaBasket(this.nombreLiga)){
					this.nombreLiga = 'ACB';
				}
				this.verLiga(this.nombreLiga);
				break;
		}
	},
	
	cambiarLiga: function(){
		this.verLiga($('liga').value);
	},
	
	cambiarLigaBsk: function(){
		this.verLiga($('ligaBsk').value);
	},
	
	verLiga: function(nombreLiga){
		this.pantalla = 0;
		if(nombreLiga == '')	return;
		var tipos = ['','Uno','Dos','Tres','Cuatro'];
		$('ft_prim').className = 'bt_division_' + tipos[this.tipoWidget];
		$('ft_segn').className = 'bt_division_' + tipos[this.tipoWidget];
		$('ft_calc').className = 'bt_division_' + tipos[this.tipoWidget];
		$('ft_prem').className = 'bt_Premier_' + tipos[this.tipoWidget];
		//$('ft_bund').className = 'bt_Bundes_' + tipos[this.tipoWidget];
		$('ft_cham').className = 'bt_Bundes_' + tipos[this.tipoWidget];
		$('bk_acb').className  = 'bt_inicio_' + tipos[this.tipoWidget];
		$('bk_nba').className  = 'bt_inicio_' + tipos[this.tipoWidget];
		$('bk_euro').className  = 'bt_Bundes_' + tipos[this.tipoWidget];
		//$('bk_bbl').className  = 'bt_inicio_' + tipos[this.tipoWidget];
		//$('bk_legaa').className  = 'bt_inicio_' + tipos[this.tipoWidget];
		
		switch(nombreLiga){
			case 'PRIMERA': $('ft_prim').className = 'bt_division_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'SEGUNDA': $('ft_segn').className = 'bt_division_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'CALCIO': $('ft_calc').className = 'bt_division_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'PREMIER': $('ft_prem').className = 'bt_Premier_' + tipos[this.tipoWidget] + 'Activo'; break;
			//case 'BUNDESLIGA': $('ft_bund').className = 'bt_Bundes_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'CHAMPIONS': $('ft_cham').className = 'bt_Bundes_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'ACB': $('bk_acb').className  = 'bt_inicio_' + tipos[this.tipoWidget] + 'Activo'; break;
			//case 'BBL': $('bk_bbl').className  = 'bt_inicio_' + tipos[this.tipoWidget] + 'Activo'; break;
			//case 'LEGA A': $('bk_legaa').className = 'bt_inicio_' + tipos[this.tipoWidget] + 'Activo'; break;
			case 'BUNDESLIGA': case 'FRANCIA': case 'PORTUGAL': case 'HOLANDA': case 'ARGENTINA': case 'RUSIA': case 'BRASIL': 
				$('selec_ligaFut').value = nombreLiga; break;
			case 'LEGA A': case 'LNB': case 'BBL': case 'GRE-BK': case 'ISR-BK': case 'TUR-BK': case 'RUS-BK': 
				$('selec_ligaBsk').value = nombreLiga; break;
			case 'EUROLIGA':	$('bk_euro').className = 'bt_Bundes_' + tipos[this.tipoWidget] + 'Activo'; break;
			//case 'EUROPA LEAGUE': case 'EUROCHALLENGE':
			//	document.location.href = document.location.href = '/widgets/widget'+this.tipoWidget+'B.php?deporte='+nombreLiga; return; break;
			case 'OTRAS': window.open(this.destinoLink,'_blank');	return;	break;
		}
		
		
		this.nombreLiga = nombreLiga;
		this.jornada = null;
		this.inicialSN = false;
		this.cargarPartidos();
	},
	
	verJornadaSiguiente: function(){
		this.jornada++;
		this.cargarPartidos();
	},

	verJornadaAnterior: function(){
		this.jornada--;
		this.cargarPartidos();
	},

	verJornadaSelect: function(valor){
		this.inicialSN = false;
		this.jornada = valor;
		this.pantalla = 0;
		this.cargarPartidos();
	},
	
	crearParametrosBusqueda: function(){
		var pais; var liga;
		switch(this.nombreLiga){
			case 'PRIMERA': 		pais = 'SPAIN'; 	liga = 87;	break;
			case 'SEGUNDA': 		pais = 'SPAIN'; 	liga = 140;	break;
			case 'PREMIER': 		pais = 'ENGLAND'; 	liga = 47; 	break;
			case 'CALCIO': 			pais = 'ITALY'; 	liga = 55; 			break;
			
			case 'ACB': 			pais = 'SPAIN'; 	liga = 395;	break;
			case 'NBA': 			pais = 'USA'; 		liga = 390; 				break;
			case 'BBL': 			pais = 'GERMANY'; 	liga = 393;	break;
			case 'EUROLIGA': 		pais = 'EUROPE'; 	liga = 399;	break;
			case 'EUROCHALLENGE':	pais = 'EUROPE';	liga = 400; break;

			case 'BUNDESLIGA': 		pais = 'GERMANY'; 	liga = 54; 		break;
			case 'FRANCIA': 		pais = 'FRANCE'; 	liga = 53;			break;
			case 'GRECIA':			pais = 'GREECE'; 	liga = 'DIVISION 1';		break;
			case 'PORTUGAL':		pais = 'PORTUGAL';	liga = 61;	break;
			case 'HOLANDA': 		pais = 'HOLLAND'; 	liga = 57;		break;
			case 'ARGENTINA':		pais = 'ARGENTINA';	liga = 112;			break;
			case 'BRASIL':			pais = 'BRAZIL';	liga = 268;		break;
			case 'RUSIA':			pais = 'RUSSIA';	liga = 63;		break;
			case 'CHAMPIONS':		pais = 'EUROPE';	liga = 42;		break;
			case 'EUROPA LEAGUE':	pais = 'EUROPE';	liga = 73;		break;
			//case 'BELGICA': 		pais = 'BELGIUM'; 	liga = 'DIVISION 1';		break;

			case 'LNB':				pais = 'FRANCE';	liga = 398;	break;
			case 'LEGA A':			pais = 'ITALY';		liga = 397;	break;
			case 'GRE-BK':			pais = 'GREECE';	liga = 394;	break;
			case 'TUR-BK':			pais = 'TURKEY';	liga = 8927;	break;
			case 'ISR-BK':			pais = 'ISRAEL';	liga = 'REGULAR SEASON';	break;
			case 'RUS-BK':			pais = 'RUSSIA';	liga = 'REGULAR SEASON';	break;
		}
		this.parametrosBusqueda = {
			'gmtCliente': this.gmt,
			'deporte': (this.deporte == 'futbol')?'SOC':'BSK', 
			'pais': pais,
			'nombreLiga': liga,
			'time': Math.random(),
			'jornada': this.jornada
		};
	},
	
	cargarPartidos: function(){
		if(this.pantalla % 6 == 0){
			if(this.inicialSN == false){
				var url = '/widgets/includes/obtenerPartidosWidget.php';
				this.crearParametrosBusqueda();
			}
			else{
				var url = '/widgets/includes/obtenerPartidosWidgetDiarios.php';
				this.parametrosBusqueda = {
					'deporte': (this.deporte == 'futbol')?'SOC':'BSK', 
					'gmtCliente': this.gmt,
					'fecha': '',
					'time': Math.random(),
					'inicialSN': 1
				};
			}
			
			var myAjax = new Ajax.Request(url, {
				method: "get",
				parameters: this.parametrosBusqueda,
				//onLoading: $('tablaWidget').update('<div id="cargando"><img src="/img/loading.gif" class="cargando" /></div>'),
				onComplete: function(transport){
					wd.mostrarPartidos(transport);
				}
			});			
		}else{
			this.generarHTMLPartidos();
		}
		this.pantalla ++;
		if(this.pantalla == 1)		this.pantalla = 6;
	},
	
	recargarDatos: function(transport){
		var nuevaLista = transport.responseText.evalJSON();
		for(i = 0; i < nuevaLista.length; i++){
			var st = nuevaLista[i].starTime;
			var fecha = new Date(st.substring(0,4),st.substring(5,7)-1,st.substring(8,10),
					st.substring(11,13),st.substring(14,16) - this.gmt,st.substring(17));
			var anyoLocal = fecha.getFullYear();
			var mesLocal = fecha.getMonth() + 1;	if(mesLocal < 10) 	mesLocal = "0" + mesLocal;
			var diaLocal = fecha.getDate();			if(diaLocal < 10)	diaLocal = "0" + diaLocal;
			var horaLocal = fecha.getHours();		if(horaLocal < 10)	horaLocal = "0" + horaLocal;
			var minLocal = fecha.getMinutes();		if(minLocal < 10)	minLocal = "0" + minLocal;
			nuevaLista[i].starTime = anyoLocal + "-" + mesLocal + "-" + diaLocal + " " + horaLocal + ":" + minLocal + ":00";
			nuevaLista[i].fecha = anyoLocal + "-" + mesLocal + "-" + diaLocal;
			//alert(st + "\n" + nuevaLista[i].starTime);
		}

		if(this.inicialSN == false){
			this.listaPartidos = nuevaLista;
			this.inicialSN = true;
		}
		else{
			//var lista = transport.responseText.evalJSON();
			for(var i = 0; i < this.listaPartidos.length; i++){
				for(var j = 0; j < nuevaLista.length; j++){
					if( this.listaPartidos[i].id == nuevaLista[j].id){
						this.listaPartidos[i] = nuevaLista[j];
					}
				}
			}
		}
	},
	
	mostrarPartidos: function(transport){
		//this.listaAnterior = this.listaPartidos;
		this.recargarDatos(transport);
		if(this.listaPartidos.length > 0 && parseInt(this.listaPartidos[0].round) != 0){
			this.jornada = parseInt(this.listaPartidos[0].round);
		}
		//this.fusionarListas();
		this.generarHTMLPartidos();
	},
	
	/*fusionarListas: function(){
		this.listaFusionada.clear();
		
		for(var i = 0; i < this.listaAnterior.length; i++){
			
		}
	},*/

	generarHTMLPartidosTipo1: function(){
		var html = '';
		var htmlBotones = '';
		
		
		if(this.listaPartidos.length == 0){
			html += '<p id="noPartidos">No hay partidos hoy</p>';
		
		}
		else{
			var deporteInt = (this.deporte == 'futbol')?0:1;
			var columnas = [
				[26,35,90,29,90,15],
				[26,35,86,40,86,15]
			];
			html += 
			'<table id="tablaWidget">' +
				'<colgroup width="'+columnas[deporteInt][0]+'" span="1"> </colgroup>' +
				'<colgroup width="'+columnas[deporteInt][1]+'" span="1"> </colgroup>' +
				'<colgroup width="'+columnas[deporteInt][2]+'" span="1"> </colgroup>' +
				'<colgroup width="'+columnas[deporteInt][3]+'" span="1"> </colgroup>' +
				'<colgroup width="'+columnas[deporteInt][4]+'" span="1"> </colgroup>' + 
				'<colgroup width="'+columnas[deporteInt][5]+'" span="1"> </colgroup>' + 
				'<tr>' + 
					'<th class="celdaAzulOscuro" scope="col">DIA</th>' + 
					'<th class="celdaAzulOscuro" scope="col">HORA</th>' + 
					'<th colspan="3" scope="col" class="celdaAzul">';

						//'<a href="javascript:wd.verJornadaAnterior();" title="Jornada Anterior" class="linkBlanco"><<  </a>JORNADA ' + 
						//cortaCadena(this.listaPartidos[0].round,2) + 
						//'<a href="javascript:wd.verJornadaSiguiente();" title="Jornada Siguiente" class="linkBlanco">   >></a>
			
			
			
			//console.log(this.listaPartidos);
			//TODO obtener las jornadas por AJAX
			// Obtener las 5 jornadas anteriores y las 5 posteriores
			html += '<select  class="select_fecha"  id="selecJornada" onchange="javascript:wd.verJornadaSelect(this.value);"></select>';
			html +=	'</th>' + 
					'<th class="celdaAzulOscuro" scope="col">TMP</th>' + 
				'</tr>';
			this.getJornadas();
			
			var offset = (this.pantalla % 3) * this.maxPartidosMostrar;
			if(offset >= this.listaPartidos.length)		offset = 0;  //alert(offset +' ' + this.listaPartidos.length);
			
			for(var i = offset; i < this.listaPartidos.length && i < this.maxPartidosMostrar + offset ; i++){
				
				var p = this.listaPartidos[i];
				var fechaTrozos = p.fecha.split('-');
				var starTimeTrozos = p.starTime.split(' ');
				
				var claseFila = (p.statusType == 'live')?'vivo':'fondoTabla';
				var esFinal = (i + 1 == this.maxPartidosMostrar || i + 1 == this.listaPartidos.length );
				var estado;
				switch(p.statusType){
					case 'sched': estado = 'Pdt'; break;
					case 'live': estado = p.minutoFutbol + "'"; break;
					case 'fin': estado = 'Fin'; break;
				}
				var resultado;
				switch(this.deporte){
					case 'futbol': resultado= p.socCurrent; break;
					case 'baloncesto': resultado = p.bskCurrent; break;
				}
				if(p.statusType == 'sched')	resultado = '-';
				
				var linkdestino = this.destinoLink;
				if(p.url_partido != null) linkdestino = p.url_partido ;
				
				var numLetras = [15,14];
				html += 
			        '<tr class="' + claseFila + (esFinal?'Final':'') + '">' +
			            '<td>' + fechaTrozos[2] + '/' + fechaTrozos[1] + '</td>' +
			            '<td>' + starTimeTrozos[1].substring(0,5) + '</td>' +
			            '<td class="txtDch"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eHome+'">' + 
							cortaCadena(p.n_eHome,numLetras[deporteInt]) + '</a></td>' +
			            '<td class="resultado' + (esFinal?'FinalTabla':'')+ '"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" class="linkResultado">' +
							 ((resultado==null)?'-':resultado) + 
						'</a></td>' +
			            '<td class="txtIzq"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eAway+'">' + 
							cortaCadena(p.n_eAway,numLetras[deporteInt]) + '</a></td>' +
			            '<td>' + estado + '</td>' + 
			        '</tr>';
	
			}
			html +=	'</table>';
		}
		var htmlBotones ='<table id="tablaBotones">' +'</table>';
		
		this.geturlClasificacion(this.destinoLink);
		
		$('contenedorWidget').update('');
		$('contenedorWidget').insert(html+htmlBotones);
	},
	
	clasificarPartidosPorDia: function(){
		var i,j;
		
		this.listaDias.clear();
		this.partidosClasificados.clear();

		var offset = (this.pantalla % 3) * this.maxPartidosMostrar;
		if(offset >= this.listaPartidos.length)		offset = 0;  //alert(offset +' ' + this.listaPartidos.length);
		
		for(i = offset; i < this.listaPartidos.length && i < this.maxPartidosMostrar + offset ; i++){
			var fecha = this.listaPartidos[i].fecha;
			
			for( j = 0; j < this.listaDias.length  && fecha != this.listaDias[j]; j++);
			if( j == this.listaDias.length){
				this.listaDias.push(fecha);
				this.partidosClasificados.push(new Array());
			}
			this.partidosClasificados[j].push(this.listaPartidos[i]);
		}
	},
	
	generarHTMLPartidosTipo2: function(){
		this.clasificarPartidosPorDia();
		
		var html = '';
		var htmlBotones = '';
		/*$('tablaWidget0').setStyle({'display':'none'});
		$('tablaWidget0').update('');
		$('tablaWidget1').setStyle({'display':'none'});
		$('tablaWidget1').update('');*/

		if(this.listaPartidos.length == 0){
			html += '<p id="noPartidos">No hay partidos hoy</p>';
			//$('tablaWidget0').update('<p id="noPartidos">No hay partidos hoy</p>');
			//$('tablaWidget1').update('');
			//$('tablaWidget0').setStyle({'display':''});
		}
		else{
			var deporteInt = (this.deporte == 'futbol')?0:1;
			var columnas = [
				[31,67,30,67,15],
				[17,65,40,65,15]
			];
			for(var h = 0; h < this.partidosClasificados.length /*&& h < 2*/ ; h++){
				var fechaTrozos = this.listaDias[h].split('-');
				
				html += 
				'<table id="tablaWidget' + h +'" ' + ((h==1)?'class="tablaDos"':'') +' >' +
					'<colgroup width="'+columnas[deporteInt][0]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][1]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][2]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][3]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][4]+'" span="1"> </colgroup>' + 
		    
					'<tr>' + 
						'<th class="celdaAzulOscuro" scope="col">HORA</th>' + 
						'<th colspan="3" class="celdaAzul" scope="col">'+
							//'<a href="javascript:wd.verJornadaAnterior();" title="Jornada Anterior"class="linkBlanco"><<  </a>' +
							'<span class="fechaW2">'+fechaTrozos[2] + '/' + fechaTrozos[1] + '</span>';
				if(h == 0){
					html += '<select  class="select_jornada"  id="selecJornada" onchange="javascript:wd.verJornadaSelect(this.value);"></select>';
					this.getJornadas();
				}
				
				html += 	
							//'<a href="javascript:wd.verJornadaSiguiente();" title="Jornada Siguiente" class="linkBlanco">  >></a>'+
						'</th>' + 
						'<th class="celdaAzulOscuro" scope="col">TMP</th>' + 
					'</tr>';
	
				for(var i = 0; i < this.partidosClasificados[h].length && i < this.maxPartidosMostrar ; i++){
					var p = this.partidosClasificados[h][i]; //this.listaPartidos[i];
					var starTimeTrozos = p.starTime.split(' ');
					
					var claseFila = (p.statusType == 'live')?'vivo':'fondoTabla';
					var esFinal = (i + 1 == this.maxPartidosMostrar || i + 1 == this.partidosClasificados[h].length );
					var estado = '';
					switch(p.statusType){
						case 'sched': estado = 'Pdt'; break;
						case 'live': estado = p.minutoFutbol + "'"; break;
						case 'fin': estado = 'Fin'; break;
					}
					var resultado;
					switch(this.deporte){
						case 'futbol': resultado= p.socCurrent; break;
						case 'baloncesto': resultado = p.bskCurrent; break;
					}
					if(p.statusType == 'sched') resultado = '-';
					
					var linkdestino = this.destinoLink;
					if(p.url_partido != null) linkdestino = p.url_partido ;
					
					var numLetras = [11,10];
					html += 
				        '<tr class="' + claseFila + (esFinal?'Final':'') + '">' +
				            '<td>' + starTimeTrozos[1].substring(0,5) + '</td>' +
				            '<td class="txtDch"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eHome+'">' + 
								cortaCadena(p.n_eHome,numLetras[deporteInt]) + '</a></td>' +
				            '<td class="resultado' + (esFinal?'FinalTabla':'')+ '"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" class="linkResultado">' +
								 ((resultado==null)?'-':resultado) + 
							'</a></td>' +
				            '<td class="txtIzq"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eAway+'">' + 
								cortaCadena(p.n_eAway,numLetras[deporteInt]) + '</a></td>' +
				            '<td>' + estado + '</td>' + 
				        '</tr>';
		
				}
				if( ! ( h + 1 < this.partidosClasificados.length && h + 1 < 2)){
				}
				
				html += '</table>';	
			}
		}
		
		var htmlBotones = '<table id="tablaBotones"></table>';
			//$('tablaBotones').update('');
			//$('tablaBotones').insert(htmlBotones);
			
		
		$('contenedorWidgets').update('');
		this.geturlClasificacion(this.destinoLink);
		$('contenedorWidgets').insert(html + htmlBotones);
		
	},

	generarHTMLPartidosTipo3: function(){
		var html = '';
		var htmlBotones = '';
		this.maxPartidosMostrar = 6;
		
		if(this.listaPartidos.length == 0){
			html += '<p id="noPartidos">No hay partidos hoy</p>';
			//$('tablaWidget0').update('<p id="noPartidos">No hay partidos hoy</p>');
			//$('tablaWidget1').update('');
		}
		else{
			var listasPartidos = new Array();
			listasPartidos.push(new Array());
			listasPartidos.push(new Array());
			for(var index = 0; index < this.listaPartidos.length; index++){
				if(index >= this.listaPartidos.length / 2){
					listasPartidos[1].push(this.listaPartidos[index]);
				}
				else{
					listasPartidos[0].push(this.listaPartidos[index]);
				}
			}
			var deporteInt = (this.deporte == 'futbol')?0:1;
			var columnas = [
				[20,28,94,29,94,15],
				[20,28,90,40,90,15]
			];
			
			var offset = (this.pantalla % 3) * this.maxPartidosMostrar;
			if(offset * 2 >= this.listaPartidos.length)		offset = 0;
			for(var h = 0; h < 2 ; h++){
				html += 
				'<table id="tablaWidget' + h + '">' +
			        '<colgroup width="'+columnas[deporteInt][0]+'" span="1"> </colgroup>' + 
			        '<colgroup width="'+columnas[deporteInt][1]+'" span="1"> </colgroup>' + 
			        '<colgroup width="'+columnas[deporteInt][2]+'" span="1"> </colgroup>' + 
			        '<colgroup width="'+columnas[deporteInt][3]+'" span="1"> </colgroup>' + 
			        '<colgroup width="'+columnas[deporteInt][4]+'" span="1"> </colgroup>' + 
			        '<colgroup width="'+columnas[deporteInt][5]+'" span="1"> </colgroup>' + 
			        '<tr>' + 
			          '<th class="celdaAzulOscuro" scope="col">DIA</th>' + 
			          '<th class="celdaAzulOscuro" scope="col">HORA</th>' + 
			          '<th  class="celdaAzul" colspan="3" scope="col">';
					  	//'<a href="javascript:wd.verJornadaAnterior();" title="Jornada Anterior" class="linkBlanco"><<  </a> JORNADA '+ cortaCadena(this.listaPartidos[0].round,2) +'<a href="javascript:wd.verJornadaSiguiente();" title="Jornada Siguiente" class="linkBlanco">  >></a>' +

					if(h == 0){
						html += '<select class="select_fecha" id="selecJornada" onchange="javascript:wd.verJornadaSelect(this.value);"></select>';
						this.getJornadas();
					}

				html +=
					  '</th>' + 
			          '<th class="celdaAzulOscuro" scope="col">TMP</th>' + 
			        '</tr>';

				for(var i = offset; i < listasPartidos[h].length && i < this.maxPartidosMostrar + offset; i++){
					var p = listasPartidos[h][i];
					var fechaTrozos = p.fecha.split('-');
					var starTimeTrozos = p.starTime.split(' ');
					
					var claseFila = (p.statusType == 'live')?'vivo':'fondoTabla';
					var esFinal = (i + 1 == this.maxPartidosMostrar || i + 1 == listasPartidos[h].length );
					var estado;
					switch(p.statusType){
						case 'sched': estado = 'Pdt'; break;
						case 'live': estado = p.minutoFutbol + "'"; break;
						case 'fin': estado = 'Fin'; break;
					}
					var resultado;
					switch(this.deporte){
						case 'futbol': resultado= p.socCurrent; break;
						case 'baloncesto': resultado = p.bskCurrent; break;
					}
					if(p.statusType == 'sched')	resultado = '-';
					
					var linkdestino = this.destinoLink;
					if(p.url_partido != null) linkdestino = p.url_partido ;
					
					var numLetras = [11,10];
					html += 
				        '<tr class="' + claseFila + (esFinal?'Final':'') + '">' +
				            '<td>' + fechaTrozos[2] + '/' + fechaTrozos[1] + '</td>' +
				            '<td>' + starTimeTrozos[1].substring(0,5) + '</td>' +
				            '<td class="txtDch"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eHome+'">' + 
								cortaCadena(p.n_eHome,numLetras[deporteInt]) +  '</a></td>' +
				            '<td class="resultado' + (esFinal?'FinalTabla':'')+ '"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" class="linkResultado">' + 
								((resultado==null)?'-':resultado) + 
							'</a></td>' +
				            '<td class="txtIzq"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eAway+'">' + 
								cortaCadena(p.n_eAway,numLetras[deporteInt]) + '</a></td>' +
				            '<td>' + estado + '</td>' + 
				        '</tr>';
		
				}
				html += '</table>';					
				//$('tablaWidget' + h).update('');
				//$('tablaWidget' + h).insert(html);
			}
		}
		var htmlBotones = '<table id="tablaBotones"></table>';
		$('contenedorWidgets').update('');
		this.geturlClasificacion(this.destinoLink);
		$('contenedorWidgets').insert(html + htmlBotones);
	},

	generarHTMLPartidosTipo4: function(){
		var html = '';
		var htmlBotones = '';
		this.maxPartidosMostrar = 4;
		
		if(this.listaPartidos.length == 0){
			html += '<p id="noPartidos">No hay partidos hoy</p>';
			//$('tablaWidget0').update('<p id="noPartidos">No hay partidos hoy</p>');
			//$('tablaWidget1').update('');
			//$('tablaWidget2').update('');
		}
		else{
			var listasPartidos = new Array();
			listasPartidos.push(new Array());
			listasPartidos.push(new Array());
			listasPartidos.push(new Array());
			
			var minItems = parseInt(this.listaPartidos.length / 3);
			var restoItems = this.listaPartidos.length % 3;
			for(var index = 0; index < this.listaPartidos.length; index++){
				if(index < minItems + ((restoItems > 1)?1:restoItems) ){
					lista = 0;
				}
				else if( index < minItems * 2 + ((restoItems > 2)?2:restoItems) ){
					lista = 1;
				}
				else{
					lista = 2;
				}
				listasPartidos[lista].push(this.listaPartidos[index]);
			}
			
			var deporteInt = (this.deporte == 'futbol')?0:1;
			var columnas = [
				    [25,36,100,40,100,15],
					[25,36,100,40,100,15]
			];
			
			var offset = (this.pantalla % 3) * this.maxPartidosMostrar;
			if(offset * 3 >= this.listaPartidos.length)		offset = 0;

			for(var h = 0; h < 3 ; h++){
				html += 
				'<table id="tablaWidget' + h + '">' + 
					'<colgroup width="'+columnas[deporteInt][0]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][1]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][2]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][3]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][4]+'" span="1"> </colgroup>' + 
					'<colgroup width="'+columnas[deporteInt][5]+'" span="1"> </colgroup>' + 

			        '<tr>' + 
			          '<th class="celdaAzulOscuro" scope="col">DIA</th>' + 
			          '<th class="celdaAzulOscuro" scope="col">HORA</th>' + 
			          '<th  class="celdaAzul" colspan="3" scope="col">';
					  	//'<a href="javascript:wd.verJornadaAnterior();" title="Jornada Anterior" class="linkBlanco"><< </a>JORNADA '+ cortaCadena(this.listaPartidos[0].round,2) +'<a href="javascript:wd.verJornadaSiguiente();" title="Jornada Siguiente" class="linkBlanco">  >></a>' +
				if(h == 0){
					html += '<select class="select_fecha"  id="selecJornada" onchange="javascript:wd.verJornadaSelect(this.value);"></select>';
					this.getJornadas();
				}

				html +=
					  '</th>' + 
			          '<th class="celdaAzulOscuro" scope="col">TMP</th>' + 
			        '</tr>';
		
				for(var i = offset; i < listasPartidos[h].length && i < this.maxPartidosMostrar + offset; i++){
					var p = listasPartidos[h][i];
					var fechaTrozos = p.fecha.split('-');
					var starTimeTrozos = p.starTime.split(' ');
					
					var claseFila = (p.statusType == 'live')?'vivo':'fondoTabla';
					var esFinal = (i + 1 == this.maxPartidosMostrar || i + 1 == listasPartidos[h].length );
					var estado;
					switch(p.statusType){
						case 'sched': estado = 'Pdt'; break;
						case 'live': estado = p.minutoFutbol + "'"; break;
						case 'fin': estado = 'Fin'; break;
					}
					var resultado;
					switch(this.deporte){
						case 'futbol': resultado= p.socCurrent; break;
						case 'baloncesto': resultado = p.bskCurrent; break;
					}
					if(p.statusType == 'sched'){
						resultado = '-';
					}
					var linkdestino = this.destinoLink;
					if(p.url_partido != null) linkdestino = p.url_partido ;
					
					var numLetras = [14,13];
					html += 
				        '<tr class="' + claseFila + (esFinal?'Final':'') + '">' +
				            '<td>' + fechaTrozos[2] + '/' + fechaTrozos[1] + '</td>' +
				            '<td>' + starTimeTrozos[1].substring(0,5) + '</td>' +
				            '<td class="txtDch"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eHome+'">' + 
								cortaCadena(p.n_eHome,numLetras[deporteInt]) + '</a></td>' +
				            '<td class="resultado' + (esFinal?'FinalTabla':'')+ '"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" class="linkResultado">' +
								 ((resultado==null)?'-':resultado) + 
							'</a></td>' +
				            '<td class="txtIzq"><a onclick="clicWidget();" href="'+linkdestino+'" target="_blank" title="'+p.n_eAway+'">' + 
								cortaCadena(p.n_eAway,numLetras[deporteInt]) + 	'</a></td>' +
				            '<td>' + estado + '</td>' + 
				        '</tr>';
		
				}
				html += '</table>';
					
				//$('tablaWidget' + h).update('');
				//$('tablaWidget' + h).insert(html);
			}
			
		}
		var htmlBotones = '<table id="tablaBotones"></table>';
		$('contenedorWidgets').update('');
		this.geturlClasificacion(this.destinoLink);
		$('contenedorWidgets').insert(html + htmlBotones);
	},
	
	generarHTMLPartidos: function(){
		switch(this.tipoWidget){
			case 1: this.generarHTMLPartidosTipo1(); break;
			case 2: this.generarHTMLPartidosTipo2(); break;
			case 3: this.generarHTMLPartidosTipo3(); break;
			case 4: this.generarHTMLPartidosTipo4(); break;
			
		}
	},
	
	yUltima: function(){
		
	},
	// Llamada ajax para obtener la url de clasificacion a partir del id del torneo o la url antigua
	geturlClasificacion: function(destinoLink){
		var url = "/widgets/getUrlClasDestino.php";
		if(this.listaPartidos.length > 0){ 
			new Ajax.Request(url, {
		        method: "get",
		        parameters: { 'id_liga' : this.listaPartidos[0].id_liga },
		        onComplete: function(t){
		        	var ret = t.responseText.evalJSON()
		        	$('tablaBotones').update(
	        			'<tr><td><a onclick="clicWidget();" target="_blank"  href="http://www.marcadoresonline.com'+ ret.clasificacion+'"  class="botonClasif">clasificaciones</a>' +
	        	   		'<a onclick="clicWidget();" target="_blank"  href="'+destinoLink+'" class="boton">ver + partidos</a></td></tr>' 
		        	);
				}
		    });	
		}
	},
	getJornadas: function(){
		var url = "/widgets/getJornadas.php";
		if(this.listaPartidos.length > 0){ 
			new Ajax.Request(url, {
		        method: "get",
		        parameters: { 'id_liga' : this.listaPartidos[0].id_liga},
		        onComplete: function(t){
		        	var html_select = "";
		        	var ret = t.responseText.evalJSON()
		        	var jornActual = wd.listaPartidos[0].round;
					for(var i = 0; i < ret.length; i++){
						jorn = ret[i];
						html_select += '<option value="'+jorn+'"' + ((jorn==jornActual)?' selected':'') +'>JORNADA '+jorn+'</option>';
					}
					
					$('selecJornada').update(html_select);
				}
		    });	
		}
	}
});

