var ie=document.all;
var nn6=document.getElementById&&!document.all;
var nn6off = nn6 ? 2 : 0;

var  bcount = 0;


function makeHttpRequest(url, callback_function, callback_obj, jsonflag )
{
	return ajaxrequest(url, callback_function, callback_obj, jsonflag );
}

function result( txt, obj )
{
	obj.innerHTML = txt;
}

function result_html( txt, obj )
{
	obj.innerHTML = txt;

	var s = obj.getElementsByTagName("SCRIPT");
	for( i = 0 ; i < s.length ; i++ )
	{
		var ns = ce('SCRIPT');
		ns.type = 'text/javascript';
		ns.text = s[i].text;
		document.body.appendChild( ns );
	}
	for( i = 0 ; i < s.length ; i++ )
		s[i].parentNode.removeChild( s[i] );
	if( isfunction( obj.onchange ) ) obj.onchange();
}

function upDom( obj, ident )
{
	while( isdefined( obj ) && obj != null )
	{
		try
		{
			var v = eval( 'obj.' + ident );
			if( isdefined( v ) )
			{
				return v;
			}
		}
		catch( err ) {}
		obj = obj.parentNode;
	}
	return null;
}

function upBrowser( obj, ident )
{
	while( isdefined( obj ) && obj != null )
	{
		try
		{
			var v = eval( 'obj.browser.ident' );
			if( isdefined( v ) && v == ident )
			{
				return obj.browser;
			}
		}
		catch( err ) {}
		obj = obj.parentNode;
	}
	return null;
}

function browser( div, url, title )
{
	this.trecs = [];
	this.arecs = [];
	this.idx = 0;
	this.pagesize = 10;
	this.more = 0;
	this.start = 0;
	this.loading = false;
	this.notfound = 'nenhum registro achado';
	this.noreturn = false;

	div.className = 'mybrowser';

	if( url.indexOf('?') == -1 ) url += '?';
	else url += '&';

	this.url = url;

	this.result = function( txt, me )
	{
		var data = json( txt );
	
		if( data == null )
		{
			me.content.innerHTML = '<div class="notfound">sem dados</div>';
			me.nav.innerHTML = '';
			return;
		}
		var start = data.start*1;
		var max = data.max;
		var nrecs = data.nrecs*1;
		var recs = data.recs;
		var labels = data.labels;
		me.data = data;
		me.labels = labels;
		me.more = data.more;
		me.nrecs = nrecs;

		for( var i = 0 ; i < nrecs ; i++ )
		{
			me.trecs[i+start] = recs[i];
			me.arecs[i+start] = new Object;
			for( var j = 0 ; j < labels.length ; j++ )
			{
				me.arecs[i+start][labels[j]] = recs[i][j];
			}
		}
		if( nrecs == 0 )
		{
			me.content.innerHTML = '<div class="notfound">' + me.notfound + '</div>';
			me.nav.innerHTML = '';
			if( isfunction( me.noreturn ) ) me.noreturn();
			return;
		}
		me.loading = false;
		me.show();
	}

	this.header = function()
	{
		var out = '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head">';
		for( var i = 0 ; i < this.labels.length ; i++ )
			out += '<td>' + this.labels[i] + '</td>';
		out += '</tr>';
		return out;
	}

	this.cell = function( rec, arec, i )
	{
		var pos = i + 1 + this.idx;
		var trclass = i & 1 ? 'impar' : 'par';
		var out = '<tr class="' + trclass + '">';
		for( var i = 0 ; i < rec.length ; i++ )
			out += '<td>' + rec[i] + '</td>';
		out += '</tr>';
		return out;
	}

	this.refresh = function( idx )
	{
		this.trecs = [];
		this.arecs = [];
		this.show( idx );
	}

	this.show = function( idx )
	{
		if( isdefined( idx ) ) this.idx = idx;
		if( !isdefined(this.trecs[this.idx]) )
		{
			this.get( this.idx );
			return;
		}
		if( this.loading ) return;

		var out = this.header();

		var last = this.trecs.length - this.idx;
		if( (last == 0 && this.more) || (last > this.pagesize) ) last = this.pagesize;

		for( var i = 0 ; i < last ; i++ )
		{
			rec = this.trecs[i+this.idx];
			arec = this.arecs[i+this.idx];
			if( isdefined( arec ) )
			{
				out += this.cell( rec, arec, i );
			}
			else
			{
				this.get( idx );
				return;
			}
		}

		out += '</table>';
		this.content.innerHTML = out;
		this.pagnav();
		ie6bg( this.content );
	}

	this.pagnav = function()
	{
		var nav = '';
		var next = this.idx + this.pagesize;
		var prev = this.idx - this.pagesize;
		this.nav.hasnext = this.nav.hasprev = false;
		if( this.idx + this.pagesize < this.trecs.length || this.more > 0 )
		{
			nav += '<div class=right><a href="javascript:;" onclick="upDom(this,\'browser\').show(' + next + ')">Próximo</a></div>';
			this.nav.hasnext = true;
		}
		if( this.idx > 0 )
		{
			nav += '<div class=left><a href="javascript:;" onclick="upDom(this,\'browser\').show(0)">Início</a> | <a href="javascript:;" onclick="upDom(this,\'browser\').show(' + prev + ')">Anterior</a></div>';
			this.nav.hasprev = true;
		}
		else nav += '<div class=left>&nbsp;</div>';
		this.nav.innerHTML = nav;
	}
	
	this.get = function( idx )
	{
		var max = this.pagesize * 4;
		var url = this.url + 'start=' + idx + '&max=' + max;
		ajaxrequest( nocache(url), this.result, this );
		this.content.innerHTML = '<div class="loading">carregando...</div>';
		if( this.debug ) debug( 'link <a href="' + url + '" target="_blank">' + url + '</a>');
//		inspect( this.content );
		watch_animate( this.content );
		this.loading = true;
	}

	this._show = this.show;
	this._get = this.get;
	this._result = this.result;
	this._cell = this.cell;
	this._header = this.header;

	this.div = div;
	this.div.browser = this;
	this.head = ce('DIV');
	this.content = ce('DIV');
	this.nav = ce('DIV');

	this.head.className = 'header';
	this.content.className = 'content';
	this.nav.className = 'nav ';

	div.appendChild( this.head );
	div.appendChild( this.content );
	div.appendChild( this.nav );

	this.head.innerHTML = title;

	return this;
}


function ie6bg( obj )
{
	if( !ie6 ) return;
	function back( o )
	{
		if( (o.currentStyle.backgroundImage) != 'none' )
		{
			var url = o.currentStyle.backgroundImage + '';
			o.style.color = 'black';
			var c = '';
			if( url.match( /header/ ) ) c = '#aaa';
			else if( url.match( /impar/ ) ) c = '#999';
			else c = '#777';
			o.style.color = 'black';
			o.style.background = c;
			return;

			url = url.replace( /url\(\"/, '' );
			url = url.replace( /\"\)/, '' );
			o.style.background = 'transparent';
			//o.style.backgroundImage = 'url(kintool/css/x.png)';
			//url = 'http://10.10.10.233/kintool/css/x.png';
			o.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='" + url + "')";
		}
	}

	var olist = obj.getElementsByTagName("TR");
	for( var i = 0 ; i < olist.length ; i++ )
		back( olist[i] );
	var olist = obj.getElementsByTagName("TD");
	for( var i = 0 ; i < olist.length ; i++ )
		back( olist[i] );
	var olist = obj.getElementsByTagName("DIV");
	for( var i = 0 ; i < olist.length ; i++ )
		back( olist[i] );
}

function nmedalha( pos, v )
{
	var transp = '';
	if( pos == 3 ) transp = ' style="opacity:0.5; filter:alpha(opacity=50);"';
	else if( pos == 4 ) transp = ' style="opacity:0.2; filter:alpha(opacity=20);"';
	var medalha = pos < 5 ? '<img width=12 height=15 src="/kintool/css/medalha_' + pos + '.gif" align="left"' + transp + '>' : '';
	return v*1 > 0 ? medalha + v : '&nbsp;';
}

function medalhas( div, url, title, classname )
{
	var o = new browser( div, url, title );

	o.ident = 'medalhabrowser';
	o.div.className += ' ' + classname;
	o._result = o.result;
	o.notfound = 'sem resultados na presente data';

	o.header = function()
	{
		return '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head"><td class="pos">Pos.</td><td>Apelido</td><td class="num">1º</td><td class="num">2º</td><td class="num">3º-4º</td><td class="num">5º-8º</td><td class="num">9º-16º</td></tr>';
	}

	o.cell = function( rec, arec, i )
	{
		var pos = i + 1 + this.idx;
		var trclass = i & 1 ? 'impar' : 'par';
		return '<tr class="' + trclass + '"><td class="pos">' + pos + '</td><td><div class="nick"><a href="javascript:;" onclick="upBrowser(this,\'medalhabrowser\').clickuser(' + (i+this.idx) + ', this)">' + arec.nome + '</a></div></td><td class="num">' + nmedalha( 0, arec.medalhas[0] ) + '</td><td class="num">' + nmedalha( 1, arec.medalhas[1] ) + '</td><td class="num">' + nmedalha( 2, arec.medalhas[2] ) + '</td><td class="num">' + nmedalha( 3, arec.medalhas[3] ) + '</td><td class="num">' + nmedalha( 4, arec.medalhas[4] );
	}

	o.clickuser = function( i, obj )
	{
		nobubble();
		sbubble( '<div id="userdetail">', getTop( obj ), getLeft( obj )+Math.floor(obj.offsetWidth/2), 510, 1, 'SW' );
		document.body.onmousedown = bubbleoutcheck;
//		return;
		var usr = o.arecs[i].eequipe*1 ? 'equipe' : 'usr';
		var d = conquistas( $('userdetail'), '/cgi-bin/sinuca/campeonatoconquista.cgi?o=desc&' + usr + '=' + o.arecs[i].id, 'Conquistas de ' + o.arecs[i].nome, 'conquistas' );
		d.show();
	}
	return o;
}

function medalhas_simples( div, url, title, classname )
{
	var o = new medalhas( div, url, title );

	o.ident = 'medalhabrowser';
	o.div.className += ' ' + classname + ' simples';
	o.header = function()
	{
		return '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head"><td class="pos">Pos.</td><td>Apelido</td><td class="num">1º</td><td class="num">2º</td><td class="num">3º-4º</td></tr>';
	}

	o.cell = function( rec, arec, i )
	{
		var pos = i + 1 + this.idx;
		var trclass = i & 1 ? 'impar' : 'par';
		return '<tr class="' + trclass + '"><td class="pos">' + pos + '</td><td><div class="nick"><a href="javascript:;" onclick="upBrowser(this,\'medalhabrowser\').clickuser(' + (i+this.idx) + ', this)">' + arec.nome + '</a></div></td><td class="num">' + nmedalha( 0, arec.medalhas[0] ) + '</td><td class="num">' + nmedalha( 1, arec.medalhas[1] ) + '</td><td class="num">' + nmedalha( 2, arec.medalhas[2] ) + '</td>';
	}

	//o.nav.style.display = 'none';
	return o;
}



function conquistas( div, url, title, classname )
{
	var o = new browser( div, url, title );

	o.ident = 'conquista';
	o.div.className += ' ' + classname;
	o.pagesize = 6;

	o.head.innerHTML += '<div id="conquistasnum" style="font-weight: normal"></div><div class="fecha" onclick="nobubble()"></div>';
	o.header = function()
	{
		return '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head"><td class="firstcol">Data</td><td>Torneio</td><td class="num">Posição</td><td>Apelido Usado</td></tr>';
	}

	o.cell = function( rec, arec, i )
	{
		var posicao = [ '<b>Campeão</b>', '<nobr>Vice-campeão</nobr>', '<nobr>Semi-final</nobr>', '<nobr>Quartas de final</nobr>', '<nobr>Oitavas de Final</nobr>' ]
		var pos = i + 1 + this.idx;
		var trclass = i & 1 ? 'impar' : 'par';

		var camp = arec.tipo == 'FAST' ? '<td>' + arec.nomecamp + '</td>' : '<td><a href="' + arec.path + '"><div>' + arec.nomecamp + '</div></a></td>';

		return '<tr class="' + trclass + '"><td class="firstcol">' + aaaammdd2date(arec.inicio) + '</td>' + camp + '<td class="num">' + posicao[arec.posicao] + '</td><td>' + arec.cnick + '</td>';
	}

	o.get = function( idx )
	{
		this._get( idx );
		this.nav.style.display = 'none';
		var bub = upDom( div, 'bubbleobj' );
		bubbleresize( bub );
	}

	o.show = function( idx )
	{
		this._show( idx );
		
		if( isdefined( this.data ) ) $('conquistasnum').innerHTML = this.data.numcampeonatos + ' competiç' + plural( this.data.numcampeonatos, 'ão', 'ões' ) + ' disputada' + plural( this.data.numcampeonatos ) + ', ' + this.data.numconquistas + ' conquista' + plural( this.data.numconquistas ) ;
		
		var bub = upDom( div, 'bubbleobj' );
		this.nav.style.display = this.nav.hasprev || this.nav.hasnext ?  'block' : 'none';
		bubbleresize( bub );
	}

	o.cclickuser = function( i )
	{
	}
	//o.nav.style.display = 'none';
	return o;
}

function torneiosativos( div, url, title )
{
	var o = new browser( div, url, title );

	//o.debug = true;
	o.notfound = 'nenhuma competição ativa no momento';
	o.div.className += ' torneiosativos';
	o.header = function()
	{
		return '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head"><td class="firstcol">JOGO</td><td>NOME</td><td class="date">INÍCIO</td><td>DURAÇÃO</td><td class="status">STATUS</td><td>&nbsp;</td></tr>';
	}

	o.cell = function( rec, arec, i )
	{
		var trclass = i & 1 ? 'impar' : 'par';
		var iclass = arec.tipo == 'FAST' ? ( arec.esporte == 'KINUCA' ? 'inscri_fast' : 'inscri_tq') : 'inscri_kinuca';
		var lasttd = arec.inscricao*1 == 1 ? '<td class="inscri"><div class="' + iclass + '" onclick="document.location=\'' + arec.path + '\'">&nbsp;</div></a></td>' : '<td>&nbsp;</td>';
		return '<tr class="' + trclass + '"><td class="firstcol">' + arec.esporte + '</td><td><a href="' + arec.path + '"><div>' + arec.nomecamp + '</div></a></td><td>' + aaaammdd2date(arec.inicio) + '</td><td class="center">' + arec.duracao + '</td><td class="center"><a href="' + arec.path + '">' + arec.status + '</a></td>' + lasttd;
	}
	return o;
}

function torneiosencerrados( div, url, title )
{
	var o = new browser( div, url, title );
	o.notfound = 'nenhuma competição encontrada';
	o.ident = 'torneiosencerrados';
	o.div.className += ' torneiosativos torneiosencerrados';
	o.header = function()
	{
		return '<table cellpadding="0" cellspacing="0" class="table" width="100%"><tr class="head"><td class="date firstcol">DATA</td><td>NOME</td><td>CAMPEÃO</td><td>VICE</td></tr>';
	}

	o.cell = function( rec, arec, i )
	{
		var trclass = i & 1 ? 'impar' : 'par';
		var camp = arec.tipo == 'XPTO' ? '<td>' + arec.nomecamp + '</td>' : '<td><a href="' + arec.path + '"><div>' + arec.nomecamp + '</div></a></td>';
		return '<tr class="' + trclass + '"><td class="firstcol">' + aaaammdd2date(arec.inicio) + '</td>' + camp + '<td class="center nowrap"><a href="javascript:;" onclick="upBrowser(this,\'torneiosencerrados\').clickuser(' + (i+this.idx) + ', this, 0)">' + arec.nickfinalistas[0] + '</td><td class="center nowrap"><a href="javascript:;" onclick="upBrowser(this,\'torneiosencerrados\').clickuser(' + (i+this.idx) + ', this, 1)">' + arec.nickfinalistas[1] + '</a></td>';
	}

	o.clickuser = function( i, obj, idxnick )
	{
		nobubble();
		sbubble( '<div id="userdetail">', getTop( obj ), getLeft( obj )+Math.floor(obj.offsetWidth/2) );
		document.body.onmousedown = bubbleoutcheck;
		var usr = o.arecs[i].tipo == 'EQUIPES' ? 'equipe' : 'usr';
		var idusr = o.arecs[i].idfinalistas[idxnick];
		var nomeusr = o.arecs[i].nickfinalistas[idxnick];
		var d = conquistas( $('userdetail'), '/cgi-bin/sinuca/campeonatoconquista.cgi?o=desc&' + usr + '=' + idusr, 'Conquistas de ' + nomeusr, 'conquistas' );
		d.show();
	}

	return o;
}



function aaaammdd2date( str )
{
	var year = str.substr( 0, 4 );
	var month = str.substr( 4, 2 );
	var day = str.substr( 6, 2 );
	var hour = str.substr( 8, 2 );
	var minute = str.substr( 10, 2 );
	var wn = str.substr( 12, 1 );
	var week = [ 'Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado' ];
	var date = day + '/' + month + '/' + year;
	if( hour != '--' && hour*1 > 0 )
	{
		date += ' - ' + (hour*1);
		if( minute != '--' ) date += ':' + minute;
		date += 'h';
	}
	if( wn > '' ) date = week[wn*1] + ', ' + date;
	return date;
}

var currentdate = null;

function getserverdate( func )
{
	function dateresult( txt, func )
	{
		var data = json( txt );
		currentdate = data;
		if( func != null ) func();
	}
	if( !isfunction( func ) ) func = null;
	ajaxrequest( nocache('/cgi-bin/sinuca/now.cgi'), dateresult, func );
}

function temporadaano( obj, dataini, datafim, func, breakct )
{
	var out = '';
	obj.temporada = obj;
	obj.functemporada = func;
	var aini = dataini.substr( 0, 4 )*1;
	var mini = dataini.substr( 4, 2 )*1;
	var afim = datafim.substr( 0, 4 )*1;
	var mfim = datafim.substr( 4, 2 )*1;
	var usemonth = mini > 0;
	var sep = '';
	if( !usemonth ) out += '<table cellpadding="0" cellspacing="0" border="0" class="temporada">';
	for( var i = afim, ct = 0 ; i >= aini ; i-- )
	{
		if( usemonth )
		{
			if( !isdefined( breakct ) ) breakct = 7;
			out += '<table cellpadding="0" cellspacing="0" border="0" class="temporada">';
			out += '<tr><td rowspan=3 valign=top>' + i + ':</td>';
			for( var j = 12 ; j >= 1; j-- )
			{

				sj = j < 10 ? '0' + j : j + '';
				var dt = i + sj;
				if( dt >= dataini && dt <= datafim )
					out += '<td style="padding-left:8px"><a href="javascript:;" onclick="upDom(this,\'temporada\').functemporada(\'' + i + sj + '\')">' + monthname[j] + '</td>';
				else
					out += '<td class="disabled" style="padding-left:8px">' + monthname[j] + '</td>';
					
				if( j == breakct ) out += '</tr><tr>';
			}
			out += '</tr>';
			out += '</table>';
		}
		else
		{
			if( !isdefined( breakct ) ) breakct = 4;
			out += '<td style="padding-right:8px; padding-bottom: 5px;"><a href="javascript:;" onclick="upDom(this,\'temporada\').functemporada(\'' + i + '\')">' + i + '</a></td>';
			if( ct == breakct ) out += '</tr><tr>';
			ct++;
		}
	}
	if( !usemonth ) out += '</table>';
	obj.innerHTML = out;
}

function menuBarTorneio( path, selected )
{
	if( !isdefined( selected ) ) selected = '';
	var sels = [ 'home', 'historico', 'fast', 'tq', 'galeria' ];
	var lnks = [ 'main_torneio_home.html', 'main_torneio_historico.html', 'main_torneio_fast.html', 'main_torneio_taca.html', 'main_torneio_galeria.html' ];
	var txts = [ 'Torneios', 'Histórico de Torneios', 'Ranking Fast Kinuca', 'Ranking Taça Quente', 'Galeria da Fama' ];
	
	var out = '<div class="menutorneio">';
	for( var i = 0 ; i < sels.length ; i++ )
	{
		var c = selected == sels[i] ? ' class="menutorneio_sel"' : '';
		out += '<a href="http://www.desafiando.com.br/' + path + '/' + lnks[i] + '"' + c + '>' + txts[i] + '</a>';
	}


	out += '</div><div class="menutorneiobottom"></div>';
	document.write( out );
}

var monthname = [ '', 'Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez' ];
var monthname_big = [ '', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ];
