$(document).ready(function() {
	var proximo = { url : '', time : '', scheme : '', channel : '', duration : 0 };
	//proximo torneo
	$.getJSON('http://wormolympics.com/api/tournaments/next/json?callback=?', function (datos) {
		$.each(datos.tourneydata, function() {
			proximo = this;
		});
	});
	//torneos de hoy (dia actual en UTC)
	$.getJSON('http://wormolympics.com/api/tournaments/today/json?callback=?', function (datos) {
		$(".wodata").html('<ul></ul>');
		var estaproximo = false;
		$.each(datos.tourneydata, function() {
			if (proximo.url != '' && proximo.url == this.url)
				estaproximo = true;
		});
		ahora = new Date();
		utc = new Date(wo.anio, ahora.getUTCMonth(), ahora.getDate(), ahora.getUTCHours(), ahora.getUTCMinutes());
		if (! estaproximo) {
			proxdia = new Date(wo.anio, wo.mes -1, wo.dia + 1, proximo.time.split(":")[0]);
			//agregar el proximo torneo en caso de que falte menos de medio dia
			if (utc.getTime() - proxdia.getTime() < 3600000 * 12) 
				datos.tourneydata[datos.tourneydata.length] = proximo;
		}
		$.each(datos.tourneydata, function() {
			var string = '<b>' + this.scheme + '</b><br />';

			var hhmm = this.time.split(":"), sumaotro = proximo.url == this.url && !estaproximo ? 1 : 0;
			fecha = new Date(wo.anio, wo.mes - 1, wo.dia + sumaotro, hhmm[0]);
			var diferencia = utc.getTime() - fecha.getTime(), estado = '', duracion = this.duration * 3600;
			diferencia = diferencia / 1000;
			
			if (diferencia >= duracion)
				estado = '<span class="error">Terminado</span>';
			else if (diferencia >= duracion * 3 / 4)
				estado = '<span class="error">Finalizando</span>';
			else if (diferencia >= duracion / 2)
				estado = '<span class="error">En curso</span>';
			else {
				if (diferencia > -1800 && diferencia < 0)
					estado = '<span class="error"><b>Inicia en breve</b></span>';
				else if (diferencia <= 1200 && diferencia > 0)
					estado = '<span class="error"><b>&iexcl;Inscripciones en curso!</b></span>';
				else if (diferencia > 1200)
					estado = '<span class="error">Ha comenzado</span>';
			}
			string += estado + (estado != '' ? '<br />' : '');

			string += '<span class="canalwo">' + this.channel + '</span><br />';
			if (diferencia < 0)
				string += '<span class="wodura">Durará aprox.: <b>' + this.duration + ' hs.</b></span><br />';

			string += '<a title="Clic para ver la hora de este torneo en tu pa&iacute;s." href="http://www.timeanddate.com/worldclock/personal.html?hour=';
			string +=  hhmm[0] + '&min=' + hhmm[1] + '&day=' + (wo.dia + sumaotro) + '&month=' + wo.mes + '&year=' + wo.anio;
			string += '&sort=0&sec=0&cities=141%2C45%2C51%2C58%2C21%2C41%2C94%2C124%2C137%2C143%2C152%2C155%2C156%2C163%2C190%2C228%2C232%2C230%2C131">';
			string += 'Horario</a> - <a title="Clic para ver los detalles de este torneo (en ingl&eacute;s)." href="' + this.url + '">Info</a>';

			$(".wodata ul").append('<li>' + string + '</li>');
		});
	});
});

