
var cg;


var _idPaisSeleccionado         = '17960';
var _idContinenteSeleccionado   = '0';
var _idLigaSeleccionado   		= '18617'; // Primera division 2010-2011

var id_baloncesto = 23;



function iniciar(){
	_idPaisSeleccionado = $("paisHid").value;
	_idLigaSeleccionado	= $("torneoHid").value;	
	_idContinenteSeleccionado = $("continenteHid").value;
	//if($('torneoHid').value != '') {
    //	alert("torneo : " + $('torneoHid').value);
	//	cargarDatosLiga($('torneoHid').value);
	//}
	cct = new ControladorClasificacionesTenis();
	cg = new ControladorClasificaciones();
	//getMarkers();
}

function cargarDatosLiga(idLiga) {
	var url = '/clasificacion/includes/obtenerDatosLiga.php';
	var pars = {'liga' : idLiga};

	new Ajax.Request(url, {
		method: 'get',
		parameters: pars,
		asynchronous : false,
		onComplete: function(t){
			var datosLiga = t.responseText.evalJSON();
			_idPaisSeleccionado 		= datosLiga.idPais; 
			_idContinenteSeleccionado 	= datosLiga.abrContinente;
			_idLigaSeleccionado   		= idLiga;
		}
	});	
}

function switchDivMapa(){
	var nuevoDisplayElems = $('mapaLocalizador').style.display == 'none'?'none':'block';
	$('panelClasificacion').setStyle({'display' : nuevoDisplayElems});
	$('panelPartidos').setStyle({'display' : nuevoDisplayElems});
	$('logoTorneo').setStyle({'display' : nuevoDisplayElems});
	$('rastroMiga').setStyle({'display' : nuevoDisplayElems});
	
	/*switchDiv('mapaLocalizador','switchMapa',
		'<div class="botonMapa">MOSTRAR MAPA</div>',
		'<div class="botonMapa2">OCULTAR MAPA</div>');*/
}

var ControladorClasificaciones = Class.create({
	mostrarMapaAlInicio: null,
	iniciando: null,
	deporteSeleccionado: null,
	continenteSeleccionado: null,
	paisSeleccionado: null,
	proveedor: null,
	
	continentes: [],
	competiciones: [],
	torneos: [],

	resultado: null,
	clasificacion: [],
	phases: [],

	idPhaseGroupStage: null,

	partidos: [],
	ronda: null,
	ronda_actual: null,
	
	gmt: null,
	
	colores_clasificacion: [],
	
	initialize: function(){
		var d = new Date();
		this.gmt = d.getTimezoneOffset();
		this.proveedor = 'enetpulse';
		
		//España - Primera Division
		this.colores_clasificacion['5451'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Uefa1', 'Uefa2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', 'Des1', 'Des2', 'Des1');
		//España - Segunda Division
		this.colores_clasificacion['5452'] = new Array('Cham1', 'Cham2', 'Uefa1', 'Uefa2', 'Uefa1', 'Uefa2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', 'Des1', 'Des2', 'Des1', 'Des2');
		//España - Segunda Division B
		this.colores_clasificacion['5484'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', 'Uefa1', 'Des1', 'Des2', 'Des1', 'Des2');
		//Italia - Serie A
		this.colores_clasificacion['5507'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Uefa1', 'Uefa2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', 'Des1', 'Des2', 'Des1');
		//Francia - Ligue 1
		this.colores_clasificacion['5199'] = new Array('Cham1', 'Cham2', 'Cham1', 'Uefa1', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', 'Des1', 'Des2', 'Des1');
		//Inglaterra - Premier League
		this.colores_clasificacion['5261'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Uefa1' ,'1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', 'Des1', 'Des2', 'Des1');
		//Alemania - Bundesliga 1
		this.colores_clasificacion['5345'] = new Array('Cham1', 'Cham2', 'Cham1', 'Uefa1', 'Uefa2', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', 'Des1', 'Des2', 'Des1');
		//Portugal - Superliga
		this.colores_clasificacion['5356'] = new Array('Cham1', 'Cham2', 'Uefa1', 'Uefa2', 'Uefa1', '2', '1', '2', '1', '2', '1', '2', '1', '2', 'Des1', 'Des2');
		//Argentina - Torneo Apertura y Clausura
		this.colores_clasificacion['5839'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Uefa1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2');
		//Brasil - Serie A 
		this.colores_clasificacion['5125'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Uefa1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2', '1', '2');
		//Champions League
		this.colores_clasificacion['5279'] = new Array('Cham1', 'Cham2', 'Uefa1', '1');
		//Europa League
		this.colores_clasificacion['5280'] = new Array('Cham1', 'Cham2', '1', '2');
		//España - ACB
		this.colores_clasificacion['5560'] = new Array('Cham1', 'Cham2', 'Cham1', 'Cham2', 'Cham1', 'Cham2', 'Cham1', 'Cham2', '1', '2', '1', '2', '1', '2', '1', '2', 'Des1', 'Des2');
		//España - LEB
		this.colores_clasificacion['5542'] = new Array('Cham1', 'Uefa1', 'Uefa2', 'Uefa1', 'Uefa2', 'Uefa1', 'Uefa2', 'Uefa1', 'Uefa2', '2', '1', '2', '1', '2', '1', '2', 'Des1', 'Des2');
		
				
		cg = this;
		this.iniciando = true;
		this.cargarContinentes();
		this.seleccionarDeporte(parseInt($('deporteHid').value),true);		
	},
	
	// generales
	rastroMiga: function(competicion,torneo){
		if (this.deporteSeleccionado != 2) {
			var rastroMiga2 = '';
			var logoTorneo = '';
			var i;
			var urlLogoTorneo;
			
			if (competicion != null && this.competiciones != null) {
				for (i = 0; i < this.competiciones.length; i++) {
				
					var competicion_id;					
					competicion_id = this.competiciones[i].codigo_enet;
					
					
					if (competicion_id == competicion) {
						if (this.competiciones[i].continente == null) {
							this.competiciones[i].continente = '';
						}
						//if(this.competiciones[i].continente != ''){
						var nombreContinente = this.competiciones[i].continente;
						for (var j = 0; j < this.continentes.length; j++) {
							if (this.competiciones[i].continente == this.continentes[j].sigla) {
								nombreContinente = this.continentes[j].nombre;
							}
						}
						rastroMiga2 += nombreContinente + ' ';
						if(this.continenteSeleccionado.sigla == 'OT') {
							 var selPais = $('pais2');
							 rastroMiga2 += selPais.options[selPais.selectedIndex].text;
						}
						else rastroMiga2 +=(this.competiciones[i].nombre_pais != null ? this.competiciones[i].nombre_pais : this.competiciones[i].nombre);
						switch (this.deporteSeleccionado) {
							case 1:
								urlLogoTorneo = this.competiciones[i].logotipo_grande;
								break;
							case id_baloncesto:
								urlLogoTorneo = this.competiciones[i].logotipo_baloncesto;
								break;
						}
					}
				}
			}
			else {
				switch (this.deporteSeleccionado) {
					case 1:
						urlLogoTorneo = '/img/logosLigas/soccer.gif';
						break;
					case id_baloncesto:
						urlLogoTorneo = '/img/logosLigas/basket.gif';
						break;
				}
			}
			logoTorneo = '<img src="' + urlLogoTorneo + '" alt="" width="89" height="89" />';
			if (torneo != null && this.torneos != null) {
				for (i = 0; i < this.torneos.length; i++) {
					if (this.torneos[i].id == torneo) {
						rastroMiga2 += ' ' + this.torneos[i].name;
					}
				}
			}
			
			$('rastroMiga').update(rastroMiga2);
			$('logoTorneo').update(logoTorneo);
			$('rastroMiga').style.display = rastroMiga2 == '' ? 'none' : '';
			$('logoTorneo').style.display = rastroMiga2 == '' ? 'none' : '';
		}
	},

	limpiarDivsResultados: function(){
		$('panelClasificacion').update('');
		$('panelPartidos').update('');
		$('logoTorneo').update('');
		$('rastroMiga').update('');
	},
	
	// primer paso --> deporte
	seleccionarDeporte: function(deporte,inicialSN){
		if(!inicialSN)		$('torneoHid').value = '';
			if (this.deporteSeleccionado != deporte) {
				if(eval($('selecFutbol'))) {
					$('selecFutbol').className = '';
					$('selecFutbol').innerHTML='<a href="javascript:cg.seleccionarDeporte(1,false);" class="menuIzqSub" >Futbol</a>';
				}
				
				if(eval($('selecBaloncesto'))) { 
					$('selecBaloncesto').className = '';
					$('selecBaloncesto').innerHTML='<a href="javascript:cg.seleccionarDeporte('+id_baloncesto+',false);" class="menuIzqSub">Baloncesto</a>';
				}
				if(eval($('selecTenis'))) {
					$('selecTenis').className = '';
					$('selecTenis').innerHTML='<a href="javascript:cg.seleccionarDeporte(2,false);" class="menuIzqSub">Tenis</a>';
				}
				//$('selecHockey').className = '';
				//$('selecBeisbol').className = '';
				//$('selecFutbolAmericano').className = '';
				
				//$('selecHockey').update('<a href="javascript:cg.seleccionarDeporte(4,false);" class="menuIzqSub">Hockey</a>');
				//$('selecBeisbol').update('<a href="javascript:cg.seleccionarDeporte(5,false);" class="menuIzqSub">Beisbol</a>');
				//$('selecFutbolAmericano').update('<a href="javascript:cg.seleccionarDeporte(6,false);" class="menuIzqSub">Futbol americano</a>');
				
				this.limpiarDivsResultados();
				this.deporteSeleccionado = deporte;
				$('combosSeleccionGenerales').setStyle({
					'display': this.deporteSeleccionado == 2 ? 'none' : 'block'
				});
				$('comboSeleccionTenis').setStyle({
					'display': this.deporteSeleccionado == 2 ? 'block' : 'none'
				});
				$('rastroMiga').setStyle({
					'display': 'none'
				});
				$('rastroMigaTenis').setStyle({
					'display': 'none'
				});
				$('logoTorneo').setStyle({
					'display': this.deporteSeleccionado == 2 ? 'block' : 'none'
				});
				
				$('liga').update('');
				switch (deporte) {
					case 1:
						//$('selecFutbol').className = 'activoIzq';
						if (eval($('selecFutbol'))) $('selecFutbol').innerHTML='<span class="activoIzq">Futbol</span>';
						break;
					case id_baloncesto:
						//$('selecBaloncesto').className = 'activoIzq';
						if (eval($('selecBaloncesto'))) $('selecBaloncesto').innerHTML='<span class="activoIzq">Baloncesto</span>';
						break;
					case 2:
						//$('selecTenis').className = 'activoIzq';
						//$('torneo_tenis').value='ATP-S';
						$('torneo_tenis').value='156';
						if(eval($('selecTenis'))) $('selecTenis').innerHTML='<span class="activoIzq">Tenis</span>';
						//this.continenteSeleccionado = '';
						cct.cargarClasificacionTenis();
						break;
					case 4:
						//$('selecHockey').className = 'activoIzq';
						if (eval($('selecHockey'))) $('selecHockey').update('<span class="activoIzq">Hockey</span>');
						break;
					case 5:
						//$('selecBeisbol').className = 'activoIzq';
						if (eval($('selecBeisbol'))) $('selecBeisbol').update('<span class="activoIzq">Beisbol</span>');
						break;
					case 6:
						//$('selecFutbolAmericano').className = 'activoIzq';
						if (eval($('selecFutbolAmericano'))) $('selecFutbolAmericano').update('<span class="activoIzq">Futbol americano</span>');
						break;
				}
				
				
				//$('switchMapa').setStyle({'display': (this.deporteSeleccionado == 2)?'none':'block'});
				//$('sustitutoSwitchMapa').setStyle({'display': (this.deporteSeleccionado == 10)?'block':'none'});
				//$('mapaLocalizador').setStyle({'display': (this.deporteSeleccionado == 2)?'none':'block'});
				
				this.cargarCompeticionesDeporte();
//				this.cargarCompeticionesSinContinente();
			}
	//	getMarkers();
	},
	
	// 2º paso --> continente
	cargarContinentes: function(){
		var url = '/clasificacion/includes/obtenerContinentes.php';
		
		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: '',
			onComplete: function(transport){
				cg.mostrarContinentes(transport);
			}
		});
	},
	
	mostrarContinentes: function(transport){
		this.continentes = transport.responseText.evalJSON();
		this.generarHTMLContinentes();
	},
	
	generarHTMLContinentes: function(){
		var opciones = '';
		
		for(var i = 0; i < this.continentes.length; i++){
			var cont = this.continentes[i];
			var selected = '';
			if ($("continenteHid").value != '')
				_idContinenteSeleccionado = $("continenteHid").value; 
			if(cont.sigla == _idContinenteSeleccionado) {
				selected = 'selected';
			}
			opciones += '<option value="'+i+'" ' + selected + '>' + cont.nombre + '</option>';
		}
		$('zona').update(opciones);
		this.seleccionarContinente();
	},
	
	seleccionarContinenteyPaisPorSigla: function(sigla,idPais){
		for(var i = 0; i < this.continentes.length; i++){
			if( this.continentes[i].sigla == sigla){
				$('zona').value = i;
			}
		}
		this.paisSeleccionado = idPais;
		this.seleccionarContinente();
	},
	
	seleccionarContinente: function(){
		var cont = this.continentes[$('zona').value];
		if( cont == null){
			window.setTimeout('cg.seleccionarContinente();',1000); // hala, a esperarse
			return;
		}
		this.continenteSeleccionado = cont;
		/*if( map != null){
			map.setCenter(new GLatLng(cont.latitud, cont.longitud), cont.zoom);
		}*/
		/*if($('mapaLocalizador').style.display == 'none'){
			if(this.iniciando == false || this.mostrarMapaAlInicio == true){
				switchDivMapa();
			}
		}*/

		$('liga').update('');
		this.cargarCompeticionesDeporte();
	},
	
	// tercer paso --> competicion (pais)
	cargarCompeticionesSinContinente: function(){
		var url = '/clasificacion/includes/obtenerCompeticiones.php';
		
		var pars = {
			'deporte' : this.deporteSeleccionado,
			'continente': ''
		};
		
		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			onComplete: function(transport){
				mostrarCompeticionesSinContinente(transport);
			}
		});

	},
	
	cargarCompeticionesDeporte: function(){
		var abortarCarga = this.deporteSeleccionado == null || this.continenteSeleccionado == null;
		if(abortarCarga){
			return;
		}

		var url = '/clasificacion/includes/obtenerCompeticiones.php';
		
		var pars = {
			'deporte' : this.deporteSeleccionado,
			'continente': this.continenteSeleccionado.sigla,
			'proveedor': this.proveedor
		};
		
		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			onComplete: function(transport){
				cg.mostrarCompeticionesDeporte(transport);
			}
		});
	},
	
	mostrarCompeticionesDeporte: function(transport){
		this.competiciones = transport.responseText.evalJSON();
		this.generarHTMLCompeticiones();
	},
	
	generarHTMLCompeticiones: function(){
		var opciones = '';
		
		//opciones += '<option value="">Selecciona pa&iacute;s</option>';
		for(var i = 0; i < this.competiciones.length; i++){
			var comp = this.competiciones[i];
			var selected = "";
			if(comp.id == _idPaisSeleccionado) {
				selected = "selected";
			}
			
			if(this.continenteSeleccionado.sigla == 'OT') 				
				opciones += '<option value="'+comp.codigo_enet+'"' + selected + '>' + (comp.nombre_ot) + '</option>';
			else 
				opciones += '<option value="'+comp.codigo_enet+'"' + selected + '>' + (comp.nombre_pais != null?comp.nombre_pais:comp.nombre) + '</option>';			
		}
		$('pais2').update(opciones);
		
		if(this.paisSeleccionado != null){
			$('pais2').value = this.paisSeleccionado;
		}
		if(_idPaisSeleccionado !='') {
			$('pais2').value = _idPaisSeleccionado;
		}
		if($('pais2').value == ''){
			$('pais2').selectedIndex = 0;
		}
		//cambio para que salga las ligas d1º española y la Acb por defecto por deporte.
		if ($('zona').value==0 && $('torneoHid').value=='' ){
			if (this.deporteSeleccionado==1)
				$('pais2').value=19967;
			if (this.deporteSeleccionado==id_baloncesto)
				$('pais2').value=8; ///=25249;
		}
		if (this.deporteSeleccionado != 2) {
			this.cargarTorneosCompeticion($('pais2').value);
		}
	},
	
	// 4º paso --> torneo (division)
	seleccionarPaisCompeticion: function(){
		if($('pais2').value == ""){
			return;
		}
		this.cargarTorneosCompeticion($('pais2').value);
	},
	
	cargarTorneosCompeticion: function(competicion){
		this.paisSeleccionado = competicion;
		$('panelClasificacion').update('');
		$('panelPartidos').update('');
		$('logoTorneo').update('');
		$('rastroMiga').update('');

		/*if($('mapaLocalizador').style.display != 'none'){
			switchDivMapa();
		}*/
		var url = '/clasificacion/includes/obtenerTorneos.php';
		var pars = {
			'competicion' : competicion,
			'deporte': this.deporteSeleccionado,
			'continente': this.continenteSeleccionado.sigla,
			'proveedor': this.proveedor
		};
		
		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			onComplete: function(transport){
				cg.mostrarTorneosCompeticion(transport);
			}
		});
	},
	
	mostrarTorneosCompeticion: function(transport){
		this.torneos = transport.responseText.evalJSON();
		this.generarHTMLTorneos();
	},
	
	generarHTMLTorneos: function(){
		var opciones = '';
		
		for(var i = 0; i < this.torneos.length; i++){
			var t = this.torneos[i];
			var selected = '';
			if(t.id == _idLigaSeleccionado ) {
				selected = 'selected';
			}
			opciones += '<option value="'+t.id+'" ' + selected + '>' + t.name + '</option>';
		}
		$('liga').update(opciones);
		this.cargarResultadoTorneo($('liga').value);

		if(this.torneos.length == 0){
			if(eval($('panelClasificacion'))) $('panelClasificacion').update('<p class="txtNoPartidos">Actualmente no hay ligas en juego.</p>');
		}

	},
	
	// 5º paso --> clasificacion: depende muy mucho de los otros 4 pasos
	cargarResultadoTorneo: function(torneo){		
		this.rastroMiga(this.paisSeleccionado,torneo);
				
		var url = '/clasificacion/includes/obtenerClasificacionEP.php';		
		var pars = {
			'torneo' : torneo
		};

		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			onLoading: function(){
				//$('panelClasificacion').update('<img src="/img/loading.gif" class="cargando" />');
			},
			onComplete: function(transport){
				$('panelPartidos').update('');
				if (this.deporteSelecciondo!=2)
					cg.parsearResultadoTorneo(transport);
			}
		});
	},
	
	parsearResultadoTorneo: function(transport){					
		this.resultado = transport.responseText.evalJSON();			
		this.phases = this.resultado.phases;			
		this.clasificacion = this.resultado.clasificacion;					
		
		if(this.clasificacion != null){			
			this.generarHTMLClasificacion();
			this.cargarPartidosPorTorneoyRonda();		
		}
		
		if(this.phases != null){ 
			this.generarHTMLPhases();	
		}
		if(this.clasificacion == null && this.phases == null){			
			$('panelClasificacion').update('<p class="txtNoPartidos">No hay datos para la liga seleccionada</p>');
			$('panelPartidos').update('');
		}
	},
	
	generarHTMLClasificacionFutbol: function(){		
		var max_pl = this.clasificacion[0].pl;	
		
		var i;
		for (i = 1; i < this.clasificacion.length; i++){
			if(  this.clasificacion[i].pl > max_pl) 
				max_pl = this.clasificacion[i].pl;
		}
		this.ronda = max_pl;
		this.ronda_actual = this.ronda;
		
		var htmlClas = '';
		htmlClas += 
			'<table  id="tablaClasif">' +
		  		'<colgroup span="1" width="60">' +
		        '</colgroup>' +
		        '<colgroup span="1" width="150">' +
		        '</colgroup>' +
		        '<colgroup span="17" width="20">' +
		        '</colgroup>' +
				'<colgroup span="1" width="45">' +
		        '</colgroup>' +
		        
		        '<tr>' +
		            '<td colspan="3" class="titulos" scope="col">&nbsp;</td>' +
		            '<td colspan="15" class="titJornada" scope="col">JORNADA '+max_pl+'</td>' +
		            '<td colspan="2" rowspan="2" class="titulos" scope="col">&nbsp;</td>' +
		        '</tr>' +
		          
		    '<tr>' +
		      '<td colspan="3" class="titulos" scope="col">&nbsp;</td>' +
		      '<td colspan="5" class="titTablaFut titulos bordeGris">EN CASA</td>' +
		      '<td colspan="5" class="titTablaFut titulos">FUERA</td>' +
		      '<td colspan="5" class="titTablaFut bordeGris2 titulos">TOTAL</td>' +
		    '</tr>' +
		    '<tr class="titTablaFut2celda">' +
		      '<td>POS</td>' +
		      '<td>EQUIPO</td>' +
		      '<td>PJ</td>' +
		      '<td>GA</td>' +
		      '<td>EM</td>' +
		      '<td>PE</td>' +
		      '<td>FA</td>' +
		      '<td>CO</td>' +
		      '<td >GA</td>' +
		      '<td>EM</td>' +
		      '<td>PE</td>' +
		      '<td>FA</td>' +
		      '<td>CO</td>' +
		      '<td >GA</td>' +
		      '<td>EM</td>' +
		      '<td>PE</td>' +
		      '<td>FA</td>' +
		      '<td>CO</td>' +
		      '<td>GD</td>' +
		      '<td  class="titTotal">TOTAL</td>' +
		    '</tr>';		
		
		var cantidad = this.clasificacion.length;						
		var codigo = 1;
		var equipo;
		for(i = 0 ; i < cantidad ; i++){
			equipo = this.clasificacion[i];									
			
			equipo.pl = (equipo.pl == null)?0:equipo.pl;
			equipo.Hw = (equipo.Hw == null)?0:equipo.Hw;
			equipo.Hl = (equipo.Hl == null)?0:equipo.Hl;
			equipo.Hf = (equipo.Hf == null)?0:equipo.Hf;
			equipo.Ha = (equipo.Ha == null)?0:equipo.Ha;
			equipo.Aw = (equipo.Aw == null)?0:equipo.Aw;
			equipo.Ad = (equipo.Ad == null)?0:equipo.Ad;
			equipo.Al = (equipo.Al == null)?0:equipo.Al;
			equipo.Af = (equipo.Af == null)?0:equipo.Af;
			equipo.Aa = (equipo.Aa == null)?0:equipo.Aa;
			equipo.Tw = (equipo.Tw == null)?0:equipo.Tw;
			equipo.Td = (equipo.Td == null)?0:equipo.Td;
			equipo.Tl = (equipo.Tl == null)?0:equipo.Tl;
			equipo.Tf = (equipo.Tf == null)?0:equipo.Tf;
			equipo.Ta = (equipo.Ta == null)?0:equipo.Ta;
			
			if (this.colores_clasificacion[$('liga').value] == undefined)
				codigo = i % 2 + 1;
			else
				codigo = this.colores_clasificacion[$('liga').value][i];
			
			htmlClas += 
			    '<tr class="fila' + codigo + 'Ajax">' +			  
			      '<td  class="celda' + codigo+'Ajax">' + equipo.posicion + '</td>' +
			      '<td class="alignEscudoAjax bold">'+ equipo.name + '</td>' + 
			      '<td  class="celda' + codigo+'Ajax">' + equipo.pl + '</td>' + 

				  // casa
				  '<td>' + equipo.Hw + '</td>' +
				  '<td>' + equipo.Hd + '</td>' +
				  '<td>' + equipo.Hl + '</td>' +
				  '<td>' + equipo.Hf + '</td>' +
				  '<td>' + equipo.Ha + '</td>' +
				  
				  //fuera
				  '<td class="celda' + codigo+'Ajax">' + equipo.Aw + '</td>' +
				  '<td  class="celda' + codigo+'Ajax">' + equipo.Ad + '</td>' +
				  '<td  class="celda' + codigo+'Ajax">' + equipo.Al + '</td>' +
				  '<td  class="celda' + codigo+'Ajax">' + equipo.Af + '</td>' +
				  '<td  class="celda' + codigo+'Ajax">' + equipo.Aa + '</td>' +
				  
				  //total
			      '<td >' + equipo.Tw + '</td>' +
			      '<td >' + equipo.Td + '</td>' +
			      '<td >' + equipo.Tl + '</td>' + 
			      '<td >' + equipo.Tf + '</td>' +
			      '<td >' + equipo.Ta + '</td>' +
			      '<td>' + (equipo.Tf - equipo.Ta) + '</td>' +
			      '<td class="celda' + codigo + 'Ajax textoTotalAjax" >'+ equipo.puntos + '</td>' +
			    '</tr>';

	    }
		
		htmlClas += 
		    '<tr>' +
		      '<td colspan="20" class="bordeGrisArriba">&nbsp;</td>' +
		    '</tr>' +
		    '<tr>' +
		      '<td colspan="20"><span class="titulos">POS</span>:Posición - <span class="titulos"> PJ</span>: Partidos Jugados- <span class="titulos"> GA</span>:Ganados -  <span class="titulos">EM</span>: Empatados <span class="titulos"><br />' +
		        'PE</span>:Perdidos - <span class="titulos"> FA</span>: A Favor <span class="titulos">CO</span>: En contra -  <span class="titulos">GD</span>: Gol Average</td>' +
			'</tr>' +
		  '</table>';
		    
		$('panelClasificacion').update(htmlClas);
	},
	
	generarHTMLClasificacionBaloncesto: function(){
		var max_pl = this.clasificacion[0].pl;
		var i;
		for (i = 1; i < this.clasificacion.length; i++){
			if(  this.clasificacion[i].pl > max_pl) 
				max_pl = this.clasificacion[i].pl;
		}
		this.ronda = max_pl;
		this.ronda_actual = this.ronda;
		var pintarPuntos = this.clasificacion[0].puntos != 0;
		
		var htmlClas = '';
		var celdas=pintarPuntos?9:8;
		htmlClas += 
			'<table  id="tablaClasif">' +
		     '<tbody>'+   
		        '<tr>' +
		            '<td colspan="'+celdas+'" class="titJornada" scope="col">JORNADA '+max_pl+'</td>' +
		        '</tr>' +		          		  
		        '<tr class="titTablaBsk2celda">' +
		        	'<td width="60">POS</td>' +
		        	'<td width="220">EQUIPO</td>' +
		        	'<td width="50">PJ</td>' +
		        	'<td width="50">GA</td>' +
		        	'<td width="50">PE</td>' +
		        	'<td width="50">FA</td>' +
		        	'<td width="50">CO</td>' +
		        	'<td width="50"> GD</td>' +
		        '</tr>';

		var cantidad = this.clasificacion.length;
		var equipo;
		for(i = 0 ; i < cantidad ; i++){
			equipo = this.clasificacion[i];
																										
			if (this.colores_clasificacion[$('liga').value] == undefined)
				codigo = i % 2 + 1;
			else
				codigo = this.colores_clasificacion[$('liga').value][i];
			
			if(equipo.pointsfor == null) equipo.pointsfor = equipo.Tf;
			if(equipo.pointsagainst == null) equipo.pointsagainst = equipo.Ta;
			
			htmlClas += 
			    '<tr class="fila' + codigo + 'Ajax">' +
			      '<td class="celda' + codigo + 'Ajax">' + equipo.posicion + '</td>' +
			      '<td class="alignEscudoAjax bold">'+ equipo.name + '</td>' + 
			      '<td class="celda' + codigo + 'Ajax">' + equipo.pl + '</td>' + 

				  //total
			      '<td class="celda' + codigo + 'Ajax">' + equipo.Tw + '</td>' +
			      '<td class="celda' + codigo + 'Ajax">' + equipo.Tl + '</td>' + 
			      '<td >' + equipo.pointsfor + '</td>' +
			      '<td >' + equipo.pointsagainst + '</td>' +
			      '<td>' + (equipo.pointsfor - equipo.pointsagainst) + '</td>' +			 
			    '</tr>';
	    }
		htmlClas += 
		    '<tr>' +
		      '<td colspan="20" class="bordeGrisArriba">&nbsp;</td>' +
		    '</tr>' +
		    '<tr>' +
		      '<td colspan="20"><span class="titulos">POS</span>:Posición - <span class="titulos"> PJ</span>: Partidos Jugados- <span class="titulos"> GA</span>:Ganados -  <span class="titulos">EM</span>: Empatados <span class="titulos"><br />' +
		        'PE</span>:Perdidos - <span class="titulos"> FA</span>: A Favor <span class="titulos">CO</span>: En contra -  <span class="titulos">GD</span>: Gol Average</td>' +
			'</tr>' +
			'</tbody>'+
		  '</table>';
		
		$('panelClasificacion').update(htmlClas);
	},

	generarHTMLClasificacion: function(){		
		switch (this.deporteSeleccionado) {
			case 1:
				this.generarHTMLClasificacionFutbol();
				break;
			case id_baloncesto:
				this.generarHTMLClasificacionBaloncesto();
				break;
		}
	},		
	
	generarHTMLGroupStageFutbolEP: function(grupos){				
		var html = '';		
		html += '<table>';		
		
		var columnas = 0;
		for (var j=0; j<grupos.length; j++) {
			var grupo = grupos[j];
			if (columnas == 0) {
				html += '<tr>';
				columnas++;
			}			
			html +=
				 '<td>' +
				 '<table class="tablaGruposAjax" style="vertical-align: top;">' +
					'<colgroup span="1" width="45">' +
					'</colgroup>' +
					'<colgroup span="1" width="200">' +
					'</colgroup>' +
					'<colgroup span="6" width="25">' +
					'</colgroup>' +
						'<colgroup span="1" width="40">' +
					'</colgroup>' +
					'<tr>' +
					'<td colspan="9" class="tituloPartidoAjax">' + grupo.name + '</td>' +
					'</tr>' +
					'<tr class="titTablaFutCmpAjax">' +
					'<th scope="col">POSICION</th>' +
					'<th scope="col">EQUIPO</th>' +
				      '<td>GA</td>' +
				      '<td>EM</td>' +
				      '<td>PE</td>' +
				      '<td>FA</td>' +
				      '<td>CO</td>' +
				      '<td>GD</td>' +

					'<th scope="col">PUNTOS</th>' +
					'</tr>';																									
			var num_equipos_fase = grupo.clasificacion.length;
			var clase = 1;
			for (var i=0; i<num_equipos_fase; i++) {
				grupo.clasificacion[i].Tw = (grupo.clasificacion[i].Tw == null)?0:grupo.clasificacion[i].Tw;
				grupo.clasificacion[i].Td = (grupo.clasificacion[i].Td == null)?0:grupo.clasificacion[i].Td;
				grupo.clasificacion[i].Tl = (grupo.clasificacion[i].Tl == null)?0:grupo.clasificacion[i].Tl;
				grupo.clasificacion[i].Tf = (grupo.clasificacion[i].Tf == null)?0:grupo.clasificacion[i].Tf;
				grupo.clasificacion[i].Ta = (grupo.clasificacion[i].Ta == null)?0:grupo.clasificacion[i].Ta;
				grupo.clasificacion[i].puntos = (grupo.clasificacion[i].puntos == null)?0:grupo.clasificacion[i].puntos;
				
				if (this.colores_clasificacion[$('liga').value] == undefined)
					clase = i % 2 + 1;
				else
					clase = this.colores_clasificacion[$('liga').value][i];
				
				html += 
		      '<tr class="fila'+clase+'Ajax">' +
			    '<td>' +  grupo.clasificacion[i].posicion + '</td>' +
      			'<td class="celdaAjax"><span class="textoRojoNegritaAjax">' + grupo.clasificacion[i].name + '</span></td>' +
			      '<td >' + grupo.clasificacion[i].Tw + '</td>' +
			      '<td >' + grupo.clasificacion[i].Td + '</td>' +
			      '<td >' + grupo.clasificacion[i].Tl + '</td>' + 
			      '<td >' + grupo.clasificacion[i].Tf + '</td>' +
			      '<td >' + grupo.clasificacion[i].Ta + '</td>' +
			      '<td >' + (grupo.clasificacion[i].Tf - grupo.clasificacion[i].Ta) + '</td>' +
      			'<td class="celdaTotalAjax"><span class="textoTotalAjax">' + grupo.clasificacion[i].puntos + '</span></td>' +
    		  '</tr>';							
			}			
			html += '</table>';
			if (columnas == 1) {
				html += '</td>';
				columnas++;
			}
			else if (columnas == 2){
				html += '</td></tr>';
				columnas = 0;
			}			
		}
		html += "</table>";
		$('panelClasificacion').update(html);
	},		
	
	generarHTMLGroupStageBaloncestoEP: function(grupos){
		
		var html = '';		
		html += '<table>';		
		
		var columnas = 0;
		for (var j=0; j<grupos.length; j++) {
			var grupo = grupos[j];
			if (columnas == 0) {
				html += '<tr>';
				columnas++;
			}			
			html +=
				 '<td>' +
				 '<table class="tablaGruposAjax" style="vertical-align: top;">' +
					'<colgroup span="1" width="45">' +
					'</colgroup>' +
					'<colgroup span="1" width="200">' +
					'</colgroup>' +
					'<colgroup span="5" width="25">' +					
					'<tr>' +
					'<td colspan="7" class="tituloPartidoAjax">' + grupo.name + '</td>' +
					'</tr>' +
					'<tr class="titTablaBsk2celda">' +
					'<th scope="col">POSICION</th>' +
					'<th scope="col">EQUIPO</th>' +
				      '<td>GA</td>' +				      
				      '<td>PE</td>' +
				      '<td>FA</td>' +
				      '<td>CO</td>' +
				      '<td>GD</td>' +					
					'</tr>';																									
			var num_equipos_fase = grupo.clasificacion.length;
			var clase = 1;
			for (var i=0; i<num_equipos_fase; i++) {
				if (grupo.clasificacion[i].Tw == null)
					grupo.clasificacion[i].Tw = 0;
				
				html += 
		      '<tr class="fila'+clase+'Ajax">' +
			    '<td>' +  grupo.clasificacion[i].posicion + '</td>' +
      			'<td class="celdaAjax"><span class="textoRojoNegritaAjax">' + grupo.clasificacion[i].name + '</span></td>' +
			      '<td >' + grupo.clasificacion[i].Tw + '</td>' +			      
			      '<td >' + grupo.clasificacion[i].Tl + '</td>' + 
			      '<td >' + grupo.clasificacion[i].Tf + '</td>' +
			      '<td >' + grupo.clasificacion[i].Ta + '</td>' +
			      '<td >' + (grupo.clasificacion[i].Tf - grupo.clasificacion[i].Ta) + '</td>' +      			
    		  '</tr>';	
				
				if (clase == 1)
					clase = 2;
				else
					clase = 1;
			}			
			html += '</table>';
			if (columnas == 1) {
				html += '</td>';
				columnas++;
			}
			else if (columnas == 2){
				html += '</td></tr>';
				columnas = 0;
			}			
		}
		html += "</table>";		
		$('panelClasificacion').update(html);		 
								
	},		
	
	generarHTMLGroupStageEP: function(grupos){
		switch(this.deporteSeleccionado){
			case 1: 
				this.generarHTMLGroupStageFutbolEP(grupos);
				break;
			case id_baloncesto:
				this.generarHTMLGroupStageBaloncestoEP(grupos);
				break;
		}
		
	},
	
	generarHTMLPhases: function(){ 
		var htmlClas = '';
		var htmlPhases = '';
		$('panelClasificacion').update('');
		var panelClasificacionUpdated = true;//false;		
		var partido = null;
		var claseFila = null;
		
		var grupos = this.phases.grupos;
		if (grupos.length > 0)
			this.generarHTMLGroupStageEP(grupos);
		
		var partidos = this.phases.partidos;			
		for (var i=0; i<partidos.length; i++) {
			var fase_partidos = partidos[i];
			htmlPhases += 
				'<table width="100%" class="tablaClasifJornada">' +
			    '<colgroup span="1" width="100">' + 
			    '</colgroup>' + 
			    '<colgroup span="1" width="50">' + 
			    '</colgroup>' + 
			    '<colgroup span="1" width="300">' +
			    '</colgroup>' +
			    '<tr>' +
			    '<th colspan="4" class="titJornada" scope="col">ENCUENTROS DE '+fase_partidos.name+ '</th>' +
	      		'</tr>' + 
				  '<tr class="titTablaFut2celda">' +
			        '<th scope="col">FECHA</th>' +
			        '<th scope="col">HORA</th>' +
			        '<th scope="col">ENCUENTRO</th>' +
			        '<th scope="col">RST</th>' +
				  '</tr>';
			
			claseFila = 'fila1';
			for (var j=0; j<fase_partidos.partidos.length; j++) {
				partido = fase_partidos.partidos[j];
								
				var claseFila = j % 2 == 0?'fila1':'fila2';
				var claseResult = j % 2 == 0?'celdaTotal1':'celdaTotal2';
								
				resultadoEspaciado = partido.home_result + ' - ' + partido.visit_result;
					
				var match;
				var equipos = partido.name.split('-');
				
				if(partido.home_result > partido.visit_result){
					match = '<b>'+equipos[0]+'</b> vs '+equipos[1];
				}
				else if(partido.home_result < partido.visit_result){
					match = equipos[0]+' vs <b>'+equipos[1]+'</b>';
				}
				else{
					match = equipos[0]+' vs '+equipos[1];
				}
				
				htmlPhases += 
				    '<tr class="'+claseFila+'">' +
				      '<td>'+partido.startdate.substr(8,2)+'-' + partido.startdate.substr(5,2) + '-' + partido.startdate.substr(0,4)+'</td>' + 
				      '<td>'+partido.startdate.substr(11,5)+'</td>' + 
				      '<td>'+match+'</td>' + 
				      '<td class="textoTotalAjax '+claseResult+'">'+ resultadoEspaciado
					  '</td>' + 
					'</tr>';							
			}
			htmlPhases += "</table>";
		}
					
		$('panelPartidos').update(htmlPhases);
	},
	
	// 6º paso: partidos
	cargarPartidosRondaAnterior: function(){
		if(this.ronda > 1){
			this.ronda--;
			this.cargarPartidosPorTorneoyRonda();
		}
	},
	
	cargarPartidosRondaSiguiente: function(){
		this.ronda++;
		this.cargarPartidosPorTorneoyRonda();
	},
	
	cargarPartidosPorTorneoyRonda: function(){
		var torneo; var deporte;
		if($('liga').value == ''){			
			torneo = $('torneoHid').value;
			switch(this.deporteSeleccionado){
				case 1:	deporte = 'SOC';	break;
				case id_baloncesto:	deporte = 'BSK';	break;
			}
		}
		else{			
			switch(this.deporteSeleccionado){
				case 1:
					torneo = $('liga').value;
					deporte = 'SOC';
					break;
				case id_baloncesto:
					//torneo = this.idPhaseGroupStage;
					torneo = $('liga').value;
					deporte = 'BSK';
					break;
			}
		}
		
		var url = '/clasificacion/includes/obtenerPartidos.php';
		var pars = {
			'torneo': torneo,
			'deporte': deporte,
			'ronda': this.ronda,
			'gmtCliente': this.gmt,
			'proveedor': this.proveedor
		};	
		var myAjaxLanzador = new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			onComplete: function(transport){
				cg.mostrarPartidos(transport);
			}
		});
	},
	
	mostrarPartidos: function(transport){
		this.partidos = transport.responseText.evalJSON();		
		this.generarHTMLPartidosEP();		
	},
	
	generarHTMLPartidosEP: function(){
		var htmlPartidos = '';
		
		if(this.partidos.length == 0){
			htmlPartidos = '<p class="noPartidosClasif">No hay partidos para el torneo y la jornada seleccionados</p>';
		}
		else{
			var claseCabecera;
			switch(this.deporteSeleccionado){
				case 1: claseCabecera = 'titTablaFut2celda'; break;
				case id_baloncesto: claseCabecera = 'titTablaBsk2celda'; break;
			}
	
			htmlPartidos += 
			  '<table width="100%" class="tablaClasifJornada">' +
			    '<colgroup span="1" width="100">' + 
			    '</colgroup>' + 
			    '<colgroup span="1" width="50">' + 
			    '</colgroup>' + 
			    '<colgroup span="1" width="300">' +
			    '</colgroup>' +
			    '<tr>' +
			      '<th colspan="4" class="titJornada" scope="col">ENCUENTROS JORNADA '+this.ronda+ '</th>' +
			      '</tr>' + 
			    '<tr class="' + claseCabecera + '">' +
			      '<th scope="col">FECHA</th>' +
			      '<th scope="col">HORA</th>' +
			      '<th scope="col">ENCUENTRO</th>' +
			      '<th scope="col">RST</th>' +
			    '</tr>';
			
			for(var i = 0; i < this.partidos.length; i++){
				var partido = this.partidos[i];
				var claseFila = i % 2 == 0?'fila1':'fila2';
				var claseResult = i % 2 == 0?'celdaTotal1':'celdaTotal2';
				
				var resultadoEspaciado;		
				if (this.ronda > this.ronda_actual)
					resultadoEspaciado = '-';
				else					
					resultadoEspaciado = partido.home_result + ' - ' + partido.visit_result;					
					
				var match;
				var equipos = partido.name.split('-');
				
				if(partido.home_result > partido.visit_result){
					match = '<b>'+equipos[0]+'</b> vs '+equipos[1];
				}
				else if(partido.home_result < partido.visit_result){
					match = equipos[0]+' vs <b>'+equipos[1]+'</b>';
				}
				else{
					match = equipos[0]+' vs '+equipos[1];
				}
	
				htmlPartidos += 
				    '<tr class="'+claseFila+'">' +
				      '<td>'+partido.startdate.substr(8,2)+'-' + partido.startdate.substr(5,2) + '-' + partido.startdate.substr(0,4)+'</td>' + 
				      '<td>'+partido.startdate.substr(11,5)+'</td>' + 
				      '<td>'+match+'</td>' + 
				      '<td class="textoTotalAjax '+claseResult+'">'+
					  	resultadoEspaciado+
					  '</td>' + 
				    '</tr>';
			}
			htmlPartidos += '</table>';
			
		}
		htmlPartidos += 
		  '<div id="cf_botonesTorneos">' +
			'<a class="botonTorneos" href="javascript:void(0);" onclick="javascript:cg.cargarPartidosRondaSiguiente();">Siguiente</a>'+
			'<a class="botonTorneos" href="javascript:void(0);" onclick="javascript:cg.cargarPartidosRondaAnterior();">Anterior</a>'+
		  '</div>';
		
		if (this.deporteSeleccionado != 2) {			
			$('panelPartidos').update(htmlPartidos);
		}
	},
	
	yUltima: function(){
		
	}
});

function cargarResultadoTorneo(){
	var torneo = $F('liga');
	new Ajax.Request('/clasificacion/includes/obtenerUrlTorneo.php', {
		method: 'get',
		parameters: {'torneo' : torneo },
		onComplete: function(t){
			if(t.responseText != ""){
				window.location =t.responseText; 
			}else{
				cg.cargarResultadoTorneo($('liga').value);
			}
		}
	});
}
