var enviando = false;
var tagAjax;
var tagTS = 10;

$(document).ready(function(){
	$.ajax({
        url: 'tagboard/index/comprobar',
        type: 'POST',
        dataType: 'json',
        data: {ts:tagTS},
        cache: false,
        async: true,
        success: function(data) {
        		tagTS = data.ts;
                setTimeout('tagComprobar()', 100);
        }
  });
	
	setInterval(function() {
		$('#tagOnline').load('tagboard/index/online?cache='+Math.random());
	}, 15000);

});

$(window).unload(function(){ tagAjax.abort(); });


function tagComprobar() {
	tagAjax = $.ajax({
        url: 'tagboard/index/comprobar',
        type: 'POST',
        dataType: 'json',
        data: {ts:tagTS},
        cache: false,
        async: true,
        success: function(data) {
                if( data != null)
                        tagActualizar(data);
        },
        complete: function() {
            setTimeout('tagComprobar()', 100);
        }
  });
}


function tagOcultar() {
	if ($('#tagContenido').is(':visible'))
		oculto = 1;
	else
		oculto = 0;

	if (!oculto)
		$('#principal').animate({marginLeft: '250px'}, function(){
		$('#tagContenido').slideToggle('slow');});
	else
		$('#tagContenido').slideToggle('slow', function() {
		$('#principal').animate({marginLeft: '50px'});});
	
	
	$.ajax({type: 'POST', url:'tagboard/index/ocultar', data: ({ocultar: oculto})});
}

function tagSonido() {
	if (document.getElementById('tagSonido'))
		return  document.getElementById('tagSonido').src.indexOf('activo') > 0;
	else
		return true;	
}

function tagToggleSonido() {
	if (tagSonido()) {
		 document.getElementById('tagSonido').src = 'tagboard/audio-mute.png';
		 valor = 0;
	} 
	else {
		document.getElementById('tagSonido').src = 'tagboard/audio-activo.png';
		valor = 1;
	}
	 $.ajax({type: 'POST', url:'tagboard/index/sonido', data: ({sonido: valor})});
}

function tagMaxTexto(event) {
	if (event.keyCode == 13)
	    return tagEnviar();
	
	texto = $('#tagTexto')[0];
	if (texto.value.length > 120)
		texto.value = texto.value.substring(0, 120);
}

function tagEnviar() {
	$.ajax({
		type: 'POST', 
		url:'tagboard/index/insertar', 
		async: true,
		dataType: "text",
		data: {texto: $('#tagTexto').val()},
		success: function(data) {
			enviando = true;
		}
	});
	$('#tagTexto').val('');

}




function tagActualizar(datos) {
	$('#tagMensajes').html(datos.data + $('#tagMensajes').html());
	tagTS = datos.ts;

	if (enviando)
		enviando = false;
	else
		if (tagSonido() && document.getElementById("tagBeep"))
			document.getElementById("tagBeep").play(2);
	
}


