/*******************
VOTES FUNCTIONS
BASIC FUNCTIONS
************************************/
var update_voters = false;

function menealo(user, id, htmlid, md5)
{
	var url = base_url + "backend/menealo.php";
	var content = "id=" + id + "&user=" + user + "&md5=" + md5;
	url = url + "?" + content;
	disable_vote_link(id, "...", '#FFC8AF');
	$.get(url, {},  
		 function(html) {
			if (/^ERROR:/.test(html)) {
				html = html.substring(6, html.length);
				parseAnswer(htmlid, true, html);
				updateVoters(id);
			} else {
				// Just a warning, do nothing
				if (/^WARN:/.test(html)) {
					alert(html);
				} else {
					parseAnswer (htmlid, false, html);
					updateVoters(id);
				}
			}
			reportAjaxStats('/vote');
		}
	);
}

function menealo_comment(user, id, value)
{
	var url = base_url + "backend/menealo_comment.php";
	var content = "id=" + id + "&user=" + user + "&value=" + value;
	var myid = 'comment-'+id;
	url = url + "?" + content;
	$.get(url, {}, 
		 function(html) {
			if (/^ERROR:/.test(html) || /^WARN:/.test(html)) {
				html = html.substring(6, html.length);
				alert(html);
			} else {
				vote_karma_image = html.split(",");
				votes = parseInt(vote_karma_image[0]);
				karma = parseInt(vote_karma_image[1]);
				image = vote_karma_image[2];
				$('#vc-'+id).html(votes);
				$('#vk-'+id).html(karma);
				if (image.length > 0) {
					$('#c-votes-'+id).html('<img src="'+image+'"/>');
				}
			}
			reportAjaxStats('/comment_vote');
		}
	);
}


function disable_problem_form(id) {
	$('#problem-' + id).hide();
}

function disable_vote_link(id, mess, background) {
	//$('#a-va-' + id).hide();
	//$('#a-va-' + id).html('<span>'+mess+'</span>');
	$('#a-va-' + id).html('<img src="/img/btn_zumbada.gif" alt="Ya has Zumbado esta chorrada" title="Ya has Zumbado esta chorrada" border="0" />');
	//$('#a-va-' + id).css('background', background);
	//$('#a-va-' + id).show('fast');
}

function parseAnswer (id, error, server_answer)
{
	answer = server_answer.split("~");
	linkid = answer[0];
	if (error || answer.length  != 5  || id != linkid) {
		alert(server_answer);
		disable_vote_link(id, "grr...", '#FFCBAA');
		disable_problem_form(id);
		return false;
	}
	votes = answer[1];
	negatives = answer[2];
	karma = answer[3];
	value = answer[4];
	updateLinkValues(id, votes, negatives, karma, value);
	return false;
}

function updateLinkValues (id, votes, negatives, karma, value) {
	if ($('#a-votes-' + id).html() != votes) {
		$('#a-votes-' + id).hide();
		$('#a-votes-' + id).html('<span>'+votes+'</span>');
		$('#a-votes-' + id).fadeIn('slow');
	}
	$('#a-neg-' + id).html(negatives);
	$('#a-karma-' + id).html(karma);
	if (value > 0) {
		disable_vote_link(id, "¡chachi!", '#FFFFFF');
		disable_problem_form(id);
	} else if (value < 0) {
		disable_vote_link(id, ":-(", '#FFFFFF');
		disable_problem_form(id);
	}
	return false;
}

function enablebutton (button, button2, target)
{
	var string = target.value;
	if (button2 != null) {
		button2.disabled = false;
	}
	if (string.length > 0) {
		button.disabled = false;
	} else {
		button.disabled = true;
	}
}

function checkfield (type, obj, field, boton,pagina)
{
	obj.disabled = true;
	obj.value = 'comprobando...';
	document.getElementById('img_valida_'+type).style.display = 'none';
	var url = base_url + 'backend/checkfield.php?type='+type+'&name=' + encodeURIComponent(field.value);
	$.get(url, {}, 
		 function(html) {
			if (html == 'OK') {
				//$('#'+type+'checkitvalue').html('<span style="color:black">"' + field.value + '": ' + html + '</span>');
				document.getElementById('img_valida_'+type).src = '/img/img_acepta_validacion_'+pagina+'.gif';
				document.getElementById('img_valida_'+type).alt = 'Puedes utilizarlo';
				document.getElementById('img_valida_'+type).title = 'Puedes utilizarlo';
				document.getElementById('img_valida_'+type).style.display = 'inline';
				//form.submit.disabled = '';
			} else {
				//$('#'+type+'checkitvalue').html('<span style="color:red">"' + field.value + '": ' + html + '</span>');
				document.getElementById('img_valida_'+type).src = '/img/img_error_validacion_'+pagina+'.gif';
				document.getElementById('img_valida_'+type).alt = 'Ya existe un usuario con esos datos';
				document.getElementById('img_valida_'+type).title = 'Ya existe un usuario con esos datos';
				document.getElementById('img_valida_'+type).style.display = 'inline';
				
				//form.submit.disabled = 'disabled';
			}
			//reportAjaxStats('/check_field');
			obj.disabled = false;
			obj.value = boton;
		}
	);
	return false;
}

function check_checkfield(fieldname, mess) {
	field = document.getElementById(fieldname);
	if (field && !field.checked) {
		alert(mess);
		// box is not checked
		return false;
	}
}

function report_problem(voto, user, id, md5 /*id, code*/) {
	if (voto == 0)
		return;
	if (!confirm("¿Seguro que no es contenido de humor?") ) {
		return false;
	}
	var content = "id=" + id + "&user=" + user + "&md5=" + md5 + '&value=' +voto;
	var url=base_url + "backend/problem.php?" + content;
	$.get(url, {}, 
		 function(html) {
			if (/^ERROR:/.test(html)) {
				//alert(html);
				//html = html.substring(6, html.length);
				//parseAnswer(id, true, html);
				$('#reportar_humor').html('Error!');
			} else {
				//parseAnswer(id, false, html);
				//updateVoters(id);
				$('#reportar_humor').html('Gracias!');
			}
			//reportAjaxStats('/problem');
		}
	);
	return false;
}

function updateVoters(id) {
	if (update_voters) {
		get_votes('meneos.php', 'voters', 'voters-container',1, id);
	}
}

// Get voters by Beldar <beldar.cat at gmail dot com>
// Generalized for other uses (gallir at gmail dot com)
function get_votes(program,type,container,page,id) {
	var url = base_url + 'backend/'+program+'?id='+id+'&p='+page+'&type='+type;
	$('#'+container).load(url);
	reportAjaxStats('/get_html');
}

// See http://www.shiningstar.net/articles/articles/javascript/dynamictextareacounter.asp?ID=AW
function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit)
	{
		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	}
	else
	{
		// otherwise, update 'characters left' counter	
		cntfield.innerHTML = '(quedan '+(maxlimit - field.value.length)+' letras)';
	}
}



/************************
Simple format functions
**********************************/
/*
  Code from http://www.gamedev.net/community/forums/topic.asp?topic_id=400585
  strongly improved by Juan Pedro López for http://meneame.net
  2006/10/01, jotape @ http://jplopez.net
*/

function applyTag(id, tag) {
	obj = document.getElementById(id);
	if (obj) wrapText(obj, tag, tag);
}

function wrapText(obj, tag) {
	if(typeof obj.selectionStart == 'number') {
		// Mozilla, Opera and any other true browser
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;

		if (start == end || end < start) return false;
		obj.value = obj.value.substring(0, start) +  replaceText(obj.value.substring(start, end), tag) + obj.value.substring(end, obj.value.length);
	} else if(document.selection) {
		// Damn Explorer
		// Checking we are processing textarea value
		obj.focus();
		var range = document.selection.createRange();
		if(range.parentElement() != obj) return false;
		if (range.text == "") return false;
		if(typeof range.text == 'string')
	        document.selection.createRange().text =  replaceText(range.text, tag);
	} else
		obj.value += text;
}

function replaceText(text, tag) {
		text = text.replace(/(^|\s)[\*_]([^\s]+)[\*_]/gm, '$1$2')
		text = text.replace(/([^\s]+)/gm, tag+"$1"+tag)
		return text;
}


// This function report the ajax request to stats trackers
// Only known how to do it with urchin/Google Analytics
// See http://www.google.com/support/analytics/bin/answer.py?answer=33985&topic=7292
function reportAjaxStats(page) {
	if (window.urchinTracker) {
		urchinTracker(page+'.ajax'); 
	}
}

// funciones para COMENTARIOS
function crearObjeto()
{
	var ro;
	var browser = navigator.appName;
	if(browser == 'Microsoft Internet Explorer')
	{
		ro = new ActiveXObject('Microsoft.XMLHTTP');	
	}
	else
	{
		ro = new XMLHttpRequest();	
	}
	return ro;
}
var http;
function daleAjax(url,arg,func)
{
	http = crearObjeto();
	http.open('get','/'+url+'?'+arg,true);
	eval('http.onreadystatechange = '+func+';');
	try { http.send(null); } catch(e) { alert('Se ha producido un error. Por favor, actualiza la página'); }
}

function enviar_comentario()
{
	if(document.getElementById('com_texto').value == '' || document.getElementById('com_nick').value == '')
	{
		alert('No puede haber campos vacios');	
	}
	else
	{
		document.getElementById('but_env_com').value = 'enviando...';
		document.getElementById('but_env_com').disabled = true;		
		daleAjax('comentarios_ajax.php','acc=grabar&id_usu='+document.getElementById('com_usuario').value+'&ava='+document.getElementById('com_usuario_avatar').value+'&nick='+document.getElementById('com_nick').value+'&id_cont='+document.getElementById('com_idcontenido').value+'&coment='+encodeURIComponent(document.getElementById('com_texto').value),'enviado_comentario');
	}
}

function enviado_comentario()
{
	if(http.readyState == 4)
	{
		var txt = http.responseText;
		document.getElementById('com_texto').value = '';
		document.getElementById('nuevo_comentario').innerHTML = txt;
		document.getElementById('nuevo_comentario').style.display = 'block';
		document.getElementById('but_env_com').value = 'ENVIADO';
		//document.getElementById('but_env_com').disabled = false;
	}
}

function hacer_amigo()
{
	if(http.readyState == 4)
	{
		var txt = http.responseText.split('|');
		if(txt[0] == 'chorrada')
		{
			// hacer amigo desde página de chorrada
			if(txt[1] == 'ko')
			{
				txt = 'Error, inténtalo de nuevo';	
			}
			else
			{
				if(txt[1] == 'fan') txt = '¡Este usuario es ahora tu ídolo!';
				else if(txt[1] == 'amigo') txt = '¡Ahora sois amigos!';
			}
			document.getElementById('bloque_amigos').innerHTML = txt;
		}
		else if(txt[0] == 'perfil')
		{
			// hacer amigo desde página de perfil
			if(txt[1] == 'ko')
			{
				alert('Ha ocurrido un error, por favor inténtalo de nuevo en un rato');	
			}
			else
			{
				if(txt[1] == 'fan') txt = '/img/btn_soy_idolo.gif';
				else if(txt[1] == 'amigo') txt = '/img/btn_es_amigo.gif';
				document.getElementById('img_amigo').src = txt;
				document.getElementById('img_amigo').removeAttribute('onclick');				
				document.getElementById('img_amigo').style.cursor = 'default';				
			}
		}
	}
}

function eliminar_amigo()
{
	if(http.readyState == 4)
	{
		var txt = http.responseText.split('|');
		if(txt[0] == 'perfil')
		{
			if(txt[1] == 'ko')
			{
				alert('Ha ocurrido un error, por favor inténtalo de nuevo en un rato');	
			}
			else
			{
				// otras formas de recargar: history.go(0) / window.location.href=window.location.href
				window.location.reload()
			}				
		}
	}
}

function busqueda()
{
	var url;
	var q = document.getElementById('busq_q').value;
	if(document.getElementById('busq_humor').checked)
	{
		url = 'http://humor.ozu.es/busqueda/'+q;
	}
	else if(document.getElementById('busq_google').checked)
	{
		url = 'http://buscar.ozu.es?etq=web&q='+q;
	}		
	location.href = url;	
}

function comprobar_form_registro()
{
	if(!document.getElementById('registro_condiciones').checked)
	{
		alert('Debes aceptar las condiciones legales');
		return false;
	}
	return true;
}

function subir_url()
{
	document.getElementById('cabecera_subir').innerHTML = '<div class="titulo_datos_chorrada"></div>';
	
	document.getElementById('subir_dalealplay').style.display = 'none';
	document.getElementById('subir_url').style.display = 'block';
}

function subir_dalealplay()
{
	document.getElementById('cabecera_subir').innerHTML = '<div class="titulo_datos_chorrada"></div>';
	document.getElementById('subir_dalealplay').style.display = 'block';
	document.getElementById('subir_url').style.display = 'none';
}

function direccion_de(tres,uno,dos)
{
	document.getElementById('recomendar_de_email').value = uno+'@'+dos+'.'+tres;
}

function recomendar_chorrada()
{
	document.getElementById('recomendar_error').innerHTML = '';
	document.getElementById('recomendar_enviar').disabled = true;
	document.getElementById('recomendar_enviar').value = 'enviando...';
	daleAjax('recomendar_chorrada.php','url='+encodeURI(document.getElementById('recomendar_url').value)+'&de_nick='+document.getElementById('recomendar_de_nombre').value+'&de_email='+document.getElementById('recomendar_de_email').value+'&para_nick='+document.getElementById('recomendar_para_nombre').value+'&para_email='+document.getElementById('recomendar_para_email').value+'&texto='+document.getElementById('recomendar_texto').value,'chorrada_recomendada');	
	return false;	
}

function chorrada_recomendada()
{
	if(http.readyState == 4)
	{
		var txt = http.responseText.split('|');
		if(txt[0] == 'ko')
		{
			document.getElementById('recomendar_error').innerHTML = txt[1];
		}
		else
		{
			document.getElementById('recomendar_error').innerHTML = txt[1];
		}				
		document.getElementById('recomendar_enviar').disabled = false;
		document.getElementById('recomendar_enviar').value = 'ENVIAR';				
	}	
}

function eliminar_favorito()
{
	if(http.readyState == 4)
	{
		var txt = http.responseText;
		if(txt == 'ko')
		{
			alert('Ha ocurrido un error, por favor inténtalo de nuevo en un rato');	
		}
		else
		{
			window.location.reload()
		}					
	}
}
