$(document).ready(function(){
	loadLivequery();
	eventos();
	showDetalhesPista('acao-foto')
});

function eventos(){
	addEvent('a.submit','click','submitForm(this)');
	addEvent('.lightbox-box .fechar','click','hideLightBox()');
	addEvent('.registre-box .registre-btn, #lightbox-login .explicacao a','click','showLightBoxRegistro(false)');
	addEvent('#banner-cadastro, .cadastro-btn, #reminder-cadastro-completo','click','showLightBoxRegistro(true)');
	addEvent('.fazer-login','click','showLightBoxLogin()');
	addEvent('#form-escolher-piloto','submit','escolhePiloto()');
	addEvent('.hide-message','click','hideMessage()');
	addEvent('#btn_apostar', 'click', 'submitAposta()');
	addEvent('#pista .acao a','click','showDetalhesPista($(this).attr("id"))');
	addEvent('.add-grupo','click','requestAddGrupo()');
	addEvent('.editar-grupo','click','requestEditarGrupo(event)');
	addEvent('.add-participante','click','requestAddParticipante(event)');
}

function requestAddParticipante(event){
	showLightBox();
	$('body').append('<div id="lightbox-add-participantes" class="lightbox-box"></div><!-- /lightbox-add-participantes -->');
	showLoading();
	var grupo_id = $(event.target).attr("id").split("_")[1];
	$.ajax({
		type: "GET",
		url: '/participantes/new',
		dataType: "html",
		data: 'grupo_id=' + grupo_id,
		success: function(obj){
			hideLoading();
			$('#lightbox-add-participantes').html(obj);
		}
	});
}

function requestAddGrupo(){
	showLightBox();
	$('body').append('<div id="lightbox-add-grupo" class="lightbox-box"></div><!-- /lightbox-add-grupo -->');
	showLoading();
	$.ajax({
		type: "GET",
		url: '/grupos/new',
		dataType: "html",
		success: function(obj){
			hideLoading();
			$('#lightbox-add-grupo').html(obj);
		}
	});
}

function requestEditarGrupo(event){
	showLightBox();
	$('body').append('<div id="lightbox-edit-grupo" class="lightbox-box"></div><!-- /lightbox-edit-grupo -->');
	showLoading();
	var grupo_id = $(event.target).attr("id").split("_")[1];
	$.ajax({
		type: "GET",
		url: '/grupos/' + grupo_id +'/edit',
		dataType: "html",
		success: function(obj){
			hideLoading();
			$('#lightbox-edit-grupo').html(obj);
		}
	});
}

function showDetalhesPista(id){
	var current_detalhe = id.split('acao-')[1];
	current_detalhe = $('#pista-' + current_detalhe);
	
	$('#pista-box .detalhe').each(function(){
		$(this).hide();
	});
	
	$('#pista .acao a').each(function(){
		$(this).removeClass('current');
	});
	
	current_detalhe.show();
	
	$('#'+id).addClass('current');
}

function escolhePiloto(){
	piloto = $("#form-escolher-piloto input[type=radio]:checked").val();
	if (piloto) {
		var current_pergunta = $("#form-escolher-piloto").attr("class");
		var dados = piloto.split("_");
		$("#link-"+ current_pergunta).html(dados[0]);
		$('#current-'+ current_pergunta).val(dados[1]);
		hideLightBox();
	}
	else {
		showMessageLightBox('Você precisa escolher um piloto para fazer sua aposta.','warning');
	}
	//alert($("#form-escolher-piloto input[type=radio]:checked").val());
	//alert ($("#form-escolher-piloto").attr("class"))
}

function showMessage(mensagem,tipo){
	$('#content').prepend(buildHTMLShowMessage(mensagem,tipo));
}

function showMessageLightBox(mensagem, tipo){
	$('.lightbox-box h1').after(buildHTMLShowMessage(mensagem,tipo));
}

function buildHTMLShowMessage(mensagem, tipo){
	return '<div class="flash-message"><div class="flash-message-box '+ tipo +'"><span class="ico"></span><strong>'+ mensagem +'</strong><a href="#" class="hide-message"></a></div><!-- /flash-message-box --></div><!-- /flash-message -->';
}

function hideMessage(){
	$('.flash-message').remove();
}

function requestFazLogin(){
	$('input[name=authenticity_token]');
	var form = $("#lightbox-registre-box form");
	showLoading();
	$.ajax({
		type: "POST",
		//url: 'http://bolao.tazio.com.br'+form.attr("action"),
		url: '/'+form.attr("action"),
		dataType: "html",
		data: 'login='+ $("#usuario_login").val() +'&email='+ $("#usuario_email").val() +'&password='+ $("#usuario_password").val() +'&password_confirmation='+ $("#usuario_password_confirmation").val() + '&authenticity_token='+ $('input[name=authenticity_token]').val(),
		success: function(obj){
			$('body').append(obj);
		},
		error: function(obj){
			$('body').append(obj);
		}
	});
}

function submitAposta() {
	
}

function submitForm(elem){
	$(elem).parents('form').submit();
}

function showLightBoxLogin(){
	showLightBox();
	$('body').append('<div id="lightbox-login" class="lightbox-box"></div><!-- /lightbox-login -->');
	showLoading();
	$.ajax({
		type: "GET",
		url: '/login',
		dataType: "html",
		success: function(obj){
			hideLoading();
			$('#lightbox-login').html(obj);
		}
	});
	
	/*
		$('body').append(<div id="lightbox-login" class="lightbox-box"></div><!-- /lightbox-login -->);
		showLoading();
		--
		$('#lightbox-login).html(obj);
		hideLoading();
	*/
	
	
	/* showLightBox();
	var html = '';
	html += ' \
	<div id="lightbox-login" class="lightbox-box"> \
		<a title="Fechar" class="fechar" href="#"></a> \
		<h1>Login</h1> \
		<p class="explicacao">Se você já é usuário efetue seu login, se não <a href="#">clique aqui para se registrar</a>.</p> \
		<div id="lightbox-login-box"> \
			<p><label for="login-email">Email:</label><input class="text" type="text" id="login-email" /></p> \
			<p><label for="login-senha">senha:</label><input class="text" type="password" id="login-senha" /></p> \
		</div><!-- /lightbox-login-box --> \
		<div class="acao"> \
			<a class="btn" href="#">registrar<img class="right" src="images/btn-right.png" alt="" /></a> \
		</div><!-- /acao --> \
	</div><!-- /lightbox-login -->';
	$('body').append(html); */
}

function showLightBoxRegistro(completo){
	showLightBox();
	$('body').append('<div id="lightbox-registre" class="lightbox-box completo-'+ completo +'"></div><!-- /lightbox-registre -->');
	showLoading();
	var height_lightbox = '1304px';
	$.ajax({
		type: "GET",
		url: '/signup?cadastro_completo='+completo,
		dataType: "html",
		success: function(obj){
			$('#lightbox').css('height',height_lightbox);
			hideLoading();
			$('#lightbox-registre').html(obj);
		}
	});
}

function showLightBoxFacaAposta(elem){
	var id_div = $(elem).parents('.pergunta-box').attr('id');
	showLightBox();
	var html = '';
	html += ' \
	<div id="lightbox-faca-aposta" class="lightbox-box"> \
		<a title="Fechar" class="fechar" href="#"></a> \
		<h1><img src="images/lightbox-'+ id_div.split("aposta-")[1] +'.png" alt="Primeiro lugar" /> Escolha o piloto</h1> \
		<div id="lightbox-faca-aposta-box"> \
			<table>';
			for (var i = 0;i < pilotos.length;i++) {
				html += ' \
					<tr> \
						<td><input type="radio" name="aposta-'+ id_div.split("aposta-")[1] +'-piloto" /></td> \
						<td>' + pilotos[i].nome + '</td> \
						<td><img src="images/brasil-flag.png" alt="Brasil" /></td> \
						<td>' + pilotos[i].equipe + '</td> \
						<td>999pts</td> \
						<td>1</td> \
					</tr> ';				
			}
			html += ' \
				</table> \
			</div><!-- /lightbox-faca-aposta-box --> \
			<div class="acao"> \
				<a class="btn" id="btn_seleciona_piloto" href="#">selecionar<img class="right" src="images/btn-right.png" alt="" /></a> \
			</div><!-- /acao --> \
		</div><!-- /lightbox-faca-aposta -->';
	$('body').append(html);
}

function showLightBox(){
	$('#lightbox').remove();
	$('.lightbox-box').remove();
	$('body').append('<div id="lightbox" style="width:100%; height:'+ $('#geral').height() +'px;"></div>');
	$('#lightbox').show();
}
function hideLightBox(){
	$('#lightbox').remove();
	$('.lightbox-box').remove();
}

function showLoading(){
	var html = '';
	html += '<div id="loading-lightbox"></div><img id="loading-img" src="/images/ajax-loader.gif" alt="Loading" />';
	$('.lightbox-box').append(html);
}

function hideLoading(){
	$('#loading-lightbox').remove();
	$('#loading-img').remove();
}

/**
 * addEvent - Adiciona um evento a um objeto
 */
function addEvent(id, evento, funcao) {
	$(id).livequery(function(event){
		$(this).bind(evento, function(event){
			eval(funcao);
			return false;
		});
	});
} //end addEvent

function loadLivequery() {
/* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version: 1.0.2
* Requires jQuery 1.1.3+
* Docs: http://docs.jquery.com/Plugins/livequery
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(4($){$.R($.7,{3:4(c,b,d){9 e=2,q;5($.O(c))d=b,b=c,c=z;$.h($.3.j,4(i,a){5(e.8==a.8&&e.g==a.g&&c==a.m&&(!b||b.$6==a.7.$6)&&(!d||d.$6==a.o.$6))l(q=a)&&v});q=q||Y $.3(2.8,2.g,c,b,d);q.u=v;$.3.s(q.F);l 2},T:4(c,b,d){9 e=2;5($.O(c))d=b,b=c,c=z;$.h($.3.j,4(i,a){5(e.8==a.8&&e.g==a.g&&(!c||c==a.m)&&(!b||b.$6==a.7.$6)&&(!d||d.$6==a.o.$6)&&!2.u)$.3.y(a.F)});l 2}});$.3=4(e,c,a,b,d){2.8=e;2.g=c||S;2.m=a;2.7=b;2.o=d;2.t=[];2.u=v;2.F=$.3.j.K(2)-1;b.$6=b.$6||$.3.I++;5(d)d.$6=d.$6||$.3.I++;l 2};$.3.p={y:4(){9 b=2;5(2.m)2.t.16(2.m,2.7);E 5(2.o)2.t.h(4(i,a){b.o.x(a)});2.t=[];2.u=Q},s:4(){5(2.u)l;9 b=2;9 c=2.t,w=$(2.8,2.g),H=w.11(c);2.t=w;5(2.m){H.10(2.m,2.7);5(c.C>0)$.h(c,4(i,a){5($.B(a,w)<0)$.Z.P(a,b.m,b.7)})}E{H.h(4(){b.7.x(2)});5(2.o&&c.C>0)$.h(c,4(i,a){5($.B(a,w)<0)b.o.x(a)})}}};$.R($.3,{I:0,j:[],k:[],A:v,D:X,N:4(){5($.3.A&&$.3.k.C){9 a=$.3.k.C;W(a--)$.3.j[$.3.k.V()].s()}},U:4(){$.3.A=v},M:4(){$.3.A=Q;$.3.s()},L:4(){$.h(G,4(i,n){5(!$.7[n])l;9 a=$.7[n];$.7[n]=4(){9 r=a.x(2,G);$.3.s();l r}})},s:4(b){5(b!=z){5($.B(b,$.3.k)<0)$.3.k.K(b)}E $.h($.3.j,4(a){5($.B(a,$.3.k)<0)$.3.k.K(a)});5($.3.D)1j($.3.D);$.3.D=1i($.3.N,1h)},y:4(b){5(b!=z)$.3.j[b].y();E $.h($.3.j,4(a){$.3.j[a].y()})}});$.3.L(\'1g\',\'1f\',\'1e\',\'1b\',\'1a\',\'19\',\'18\',\'17\',\'1c\',\'15\',\'1d\',\'P\');$(4(){$.3.M()});9 f=$.p.J;$.p.J=4(a,c){9 r=f.x(2,G);5(a&&a.8)r.g=a.g,r.8=a.8;5(14 a==\'13\')r.g=c||S,r.8=a;l r};$.p.J.p=$.p})(12);',62,82,'||this|livequery|function|if|lqguid|fn|selector|var|||||||context|each||queries|queue|return|type||fn2|prototype|||run|elements|stopped|false|els|apply|stop|undefined|running|inArray|length|timeout|else|id|arguments|nEls|guid|init|push|registerPlugin|play|checkQueue|isFunction|remove|true|extend|document|expire|pause|shift|while|null|new|event|bind|not|jQuery|string|typeof|toggleClass|unbind|addClass|removeAttr|attr|wrap|before|removeClass|empty|after|prepend|append|20|setTimeout|clearTimeout'.split('|'),0,{}))
}
/*** /LIVEQUERY ***/


/*** SELECIONA BROWSER ***/
var css_browser_selector = function() {
var ua=navigator.userAgent.toLowerCase(),
is=function(t){return ua.indexOf(t) != -1;},
h=document.getElementsByTagName('html')[0],
b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
var c=b+os+' js'; h.className += h.className?' '+c:c;
}();
/*** /SELECIONA BROWSER ***/

/**
 * var_dump
 */	
function var_dump(element, limit, depth)
{
	depth = depth?depth:0;
	limit = limit?limit:1;
	returnString = '<ol>';
	for(property in element)
	{
		//Property domConfig isn't accessable
		if (property != 'domConfig')
		{
			returnString += '<li><strong>'+ property + '</strong> <small>(' + (typeof element[property]) +')</small>';
			if (typeof element[property] == 'number' || typeof element[property] == 'boolean')
				returnString += ' : <em>' + element[property] + '</em>';
			if (typeof element[property] == 'string' && element[property])
				returnString += ': <div style="background:#C9C9C9;border:1px solid black; overflow:auto;"><code>' +
									element[property].replace(/</g, '<').replace(/>/g, '>') + '</code></div>';
			if ((typeof element[property] == 'object') && (depth <limit))
				returnString += var_dump(element[property], limit, (depth + 1));
			returnString += '</li>';
		}
	}
	returnString += '</ol>';
	if(depth == 0)
	{
		winpop = window.open("", "","width=800,height=600,scrollbars,resizable");
		winpop.document.write('<pre>'+returnString+ '</pre>');
		winpop.document.close();
	}
	return returnString;
}