// JavaScript Document
var site_root = '/';

function closeSession () {
	// now we're going to capture *all* the fields in the
	// form and submit it via ajax.
	// :input is a macro that grabs all input types, select boxes
	// textarea, etc.  Then I'm using the context of the form from 
	// the initial '#contactForm' to narrow down our selector

	
	// now if I join our inputs using '&' we'll have a query string
	jQuery.ajax({
	type: "POST",
	data: "chat_logout=true",
	url: site_root+"common/chat_login.php",
	cache: false,
	async: false,
		timeout: 8000,
	error: function() {
		console.log("Falha ao enviar.");
		$('.loading').remove();
	},
	success: function(r) { 
		//alert(r);
		window.location.reload();
	}
	}) // checkout http://jquery.com/api for more syntax and options on this method.
	// re-test...
	// by default - we'll always return false so it doesn't redirect the user.
	return false;
}
function reloadChatLista () {
	if ($('#chat_log').length) {
	// now we're going to capture *all* the fields in the
		// form and submit it via ajax.
		// :input is a macro that grabs all input types, select boxes
		// textarea, etc.  Then I'm using the context of the form from 
		// the initial '#contactForm' to narrow down our selector
		/*var inputs = [];
		$(':input', this).each(function() {
		inputs.push(this.name + '=' + escape(this.value));
		})*/
		// now if I join our inputs using '&' we'll have a query string
		jQuery.ajax({
		type: "GET",
		dataType: 'json',
		data: "chat_lista=true",
		url: site_root+"common/chat_lista.php",
		async: false,
		timeout: 8000,
		cache: false,
		error: function() {
			//console.log("Falha ao enviar.");
		},
		success: function(r) { 
			switch (r) {
				case 1:
				$('#footer').after(popup('<div class="popup_content_alert" style="color:red;font-weight:bold">Três ou mais usuários do chat solicitaram seu bloqueio. Seu acesso ao chat está suspenso por 3 horas</div>',"Banido",400,150));$(".popup_key").hide().delay(1000).fadeIn();
				break
				default:
			$('#chat_total_online').html(r.total);
			
			$('#chat_toggle').html('<div id="chat_log"></div><div id="chat_lista"></div>');
			if (r.total > 0) {
			var $html_lista = '<ul>';
			$.each(r.lista, function(i,item){
				$html_lista += '<li><a href="javascript:void(0);" onclick="javascript:flag_bannir(\''+item.chat_login+'\')"><img src="'+site_root+'imgs/chat_banir.png"  title="Banir usuário do chat" align="absmiddle" width="16" height="16" alt="online" /></a> <img src="'+site_root+'imgs/chat_online.png" align="absmiddle" width="16" height="16" alt="online" title="online" /> <img id="chat_flag_bannir" src="'+site_root+'img-thumb/usuarios/30_30_'+item.chat_imagem+'" align="absmiddle" alt="Usuário" /> <a href="javascript:void(0)" onClick="javascript:chatWith(\''+item.chat_login+'\')">Bate-papo com '+item.chat_login+'</a></li>';
			});
			$('#chat_lista').html($html_lista+"</ul>");
			}
			$('#chat_log').html('<img src="'+site_root+'img-thumb/usuarios/30_30_'+r.imagem+'" align="absmiddle" alt="Usuário" /> Logado como <strong>'+r.login+'</strong> [ <a href="javascript:closeSession();" id="chat_logout">sair</a> ]');
			}
			//alert(r.total);
			/**/
			
		}
		}) // checkout http://jquery.com/api for more syntax and options on this method.
		// re-test...
		// by default - we'll always return false so it doesn't redirect the user.
	}
		return false;
}
function flag_bannir ($apelido) {
	var where_to = confirm("Bannir o "+$apelido+" do chat?");
	if (where_to == true && $apelido.length >0) {
	// now we're going to capture *all* the fields in the
		// form and submit it via ajax.
		// :input is a macro that grabs all input types, select boxes
		// textarea, etc.  Then I'm using the context of the form from 
		// the initial '#contactForm' to narrow down our selector
		/*var inputs = [];
		$(':input', this).each(function() {
		inputs.push(this.name + '=' + escape(this.value));
		})*/
		// now if I join our inputs using '&' we'll have a query string
		jQuery.ajax({
		type: "GET",
		dataType: 'json',
		data: "flag=bannir&to="+$apelido,
		url: site_root+"common/chat_flags.php",
		async: false,
		timeout: 8000,
		cache: false,
		error: function() {
			//console.log("Falha ao enviar.");
		},
		success: function(r) {
			switch (r) {
				case 0:
				$('#footer').after(popup('<div class="popup_content_alert" style="color:blue;font-weight:bold">Sua solicitação foi recebida. Quando 3 ou mais usuários fizerem esta mesma solicitação o usuário será banido do chat por 3 horas.</div>',"Banido",400,150));$(".popup_key").hide().delay(1000).fadeIn();
				break
				default:
			}
		}
		}) // checkout http://jquery.com/api for more syntax and options on this method.
		// re-test...
		// by default - we'll always return false so it doesn't redirect the user.
	}
		return false;
}
function isInteger(s) {
	  return (s.toString().search(/^-?[0-9]+$/) == 0);
	}

jQuery(function($) {
	reloadChatLista();
	
	$("#chat_titulo").toggle(
		function () {
			$("#chat_toggle").slideToggle(500);
		},
		function () {
			$("#chat_toggle").slideToggle(500);
		}
	);
	$("#chat_logout").click(function() {
		closeSession();
	});
	$("body").everyTime(15000, 'chat_lista', function() {
		reloadChatLista();
	});
	$("#formChatLogin").validate({
			errorElement: "span",
			rules: {
				nome: "required"
			},
			messages: {
				nome: "Por favor, digite seu apelido para entrar"
			}
		});
	$(".formChatLogin").submit(function() {
			$('.loading').remove();
			$('.error').remove();
			$(".btnChatLogin").after('<span class="loading">processando...</span>');
			$(".btnChatLogin").attr("disabled","disabled");
			// now we're going to capture *all* the fields in the
			// form and submit it via ajax.
			// :input is a macro that grabs all input types, select boxes
			// textarea, etc.  Then I'm using the context of the form from 
			// the initial '#contactForm' to narrow down our selector
			if ($(this).valid()) {
			/*var inputs = [];
			$(':input', this).each(function() {
			inputs.push(this.name + '=' + escape(this.value));
			})*/
			var inputs = $(this).serialize();
			// now if I join our inputs using '&' we'll have a query string
			jQuery.ajax({
			type: "POST",
			dataType: 'json',
			data: inputs,
			url: this.action,
			async: false,
			timeout: 8000,
			error: function() {
				console.log("Falha ao enviar.");
				$('.loading').remove();
			},
			success: function(data) { 
				$("body").oneTime(500, 'login_chat', function() {
					switch(data) {
						case 0:
						$('#footer').after(popup('<div class="popup_content_alert" style="color:blue;font-weight:bold">Voce está logado</div>',"Sucesso",400,100));
						window.location.reload();
						//$('#torpedos_enviar').fadeOut("fast");
						$(".btnSubmit").attr("disabled","");
						break;
						default:
						$.each(data.erros, function(i,item){
							$('#'+item.name).after('<span htmlfor="'+item.name+'" generated="true" class="error">'+item.error+'</span>');
						});
						$(".btnChatLogin").attr("disabled","");
						Recaptcha.reload ();
					}
					$('.loading').remove();
					});
				}
			}) // checkout http://jquery.com/api for more syntax and options on this method.
			} else {
				$('.loading').remove();
				$(".btnChatLogin").attr("disabled","");
			}
			
			// re-test...
			// by default - we'll always return false so it doesn't redirect the user.
			return false;
	});
});
