var servidor="";

function ajaxObject(){
    var ajOb = null;
    if (window.XMLHttpRequest) {
        ajOb = new XMLHttpRequest();
    }
    else {
        ajOb = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return ajOb;
}

function nuevaRespuesta(){
    var li = document.createElement('li');
    var numrespuestas = document.getElementById('numrespuestas').value;
    numrespuestas++;
    document.getElementById('numrespuestas').value = numrespuestas;
	idunico = document.getElementById('idunico').value+'_'+numrespuestas;
	var html = '<label>' + numrespuestas + '</label>';
	html += '<input type="text" name="respuesta[' + numrespuestas + ']"/>';
	html += '<a class="eliminarelto" href="javascript:eliminarRespuesta(' + numrespuestas + ');"><img src="'+baseurl+'img/borrar.png" alt="Eliminar"/></a>';
	html += '<a class="masdatos" href="javascript:$(\'#masinforespuesta' + numrespuestas + '\').show();void(0);">Asociar mas datos a este elemento (fotos, descripción...)</a>';
	html += '<div id="masinforespuesta' + numrespuestas + '" class="masdatoselto">';
	html += '<label>Descripción</label>';
	html += '<textarea name="descripcion[' + numrespuestas + ']"></textarea>';
	html += '<label>Imagen</label>';
	html += '<input type="hidden" name="imagen[' + numrespuestas + ']" value="'+idunico+'"/>';
	html += '<iframe src="'+baseurl+'backend/upload.php?id='+idunico+'" frameborder="0" scrolling="no"></iframe>';
	html += '</div>';	
	li.innerHTML = html;
    li.setAttribute('id', 'respuesta' + numrespuestas);
    document.getElementById('lista_respuestas').appendChild(li);
}

function nuevaRespuesta2(){
    var li = document.createElement('li');
    var numrespuestas = document.getElementById('numrespuestas').value;
    numrespuestas++;
    document.getElementById('numrespuestas').value = numrespuestas;
    var max = document.getElementById('max').value;
    max++;
    document.getElementById('max').value = max;
	idunico = document.getElementById('idunico').value+'_'+max;
	var html = '<label>' + numrespuestas + '</label>';
	html += '<input type="text" name="respuesta[' + numrespuestas + ']"/>';
	html += '<a class="eliminarelto" href="javascript:eliminarRespuesta(' + numrespuestas + ');"><img src="'+baseurl+'img/borrar.png" alt="Eliminar"/></a>';
	html += '<a class="masdatos" href="javascript:$(\'#masinforespuesta' + numrespuestas + '\').show();void(0);">Asociar mas datos a este elemento (fotos, descripción...)</a>';
	html += '<div id="masinforespuesta' + numrespuestas + '" class="masdatoselto">';
	html += '<label>Descripción</label>';
	html += '<textarea name="descripcion[' + numrespuestas + ']"></textarea>';
	html += '<label>Imagen</label>';
	html += '<input type="hidden" name="imagen[' + numrespuestas + ']" value="'+idunico+'"/>';
	html += '<iframe src="'+baseurl+'backend/upload.php?id='+idunico+'" frameborder="0" scrolling="no"></iframe>';
	html += '</div>';	
	li.innerHTML = html;
    li.setAttribute('id', 'respuesta' + numrespuestas);
    document.getElementById('lista_respuestas').appendChild(li);
}


function eliminarRespuesta(id){
    var li = document.getElementById('respuesta' + id);
	if (document.getElementById('estado'+id)) {
		document.getElementById('estado'+id).value='eliminar';
		li.style.display='none';
	} else {
	    var ul = li.parentNode;
	    ul.removeChild(li);
	}
}

function votarrespuesta(puntos, id){
    var ajaxReq = ajaxObject();
    ajaxReq.open("get", baseurl+"backend/votar.php?p=" + puntos + "&id=" + id);
    ajaxReq.onreadystatechange = function(){
        if (ajaxReq.readyState == 4) {
            if (ajaxReq.responseText) {
                gracias = "<div class=label>Gracias</div>";
                document.getElementById('votar'+id).innerHTML = gracias;
                getVotos(id);
            }
        }
    };
    ajaxReq.send(null);
}

function getVotos(id){
    var ajaxReq = ajaxObject();
    ajaxReq.open("get", baseurl+"backend/votos.php?id=" + id);
    ajaxReq.onreadystatechange = function(){
        if (ajaxReq.readyState == 4) {
            if (ajaxReq.responseText) {
                datos = ajaxReq.responseText.split(";");
                var numvotos = datos[0];
                var mediavotos = datos[1].split(".");
				var puntos = datos[2];
                
                if (puntos == 1) {
                    txt = "(" + puntos + " punto)";
                }
                else {
                    txt = "(" + puntos + " puntos)";
                }
                
                document.getElementById('votos'+id).innerHTML = txt;
            }
        }
    };
    ajaxReq.send(null);
}

function mostrar(id) {
    var des = document.getElementById('descripcion' + id);	
    var ver = document.getElementById('verdescripcion' + id);		
	if (des.style.display=='block') {
		ver.innerHTML='<img src="http://www.lavozdigital.es/SysConfig/Images/Apoyo_vermas.gif"/>&nbsp;<a href="javascript:mostrar('+id+');">Más datos</a>'
		des.style.display='none';
	} else {
		ver.innerHTML='<img src="http://www.lavozdigital.es/SysConfig/Images/Apoyo_vermas.gif"/>&nbsp;<a href="javascript:mostrar('+id+');">Ocultar datos</a>'
		des.style.display='block';
	}
}


	/***************************** Comentarios **********************************/

	var ids_noticias = '';

	function getNumComentariosPortada(id) {
		ids_noticias = (ids_noticias != '') ? ids_noticias + '|' + id : id;
		if(window.document.getElementById('num-comentarios-' + id)) window.document.getElementById('num-comentarios-' + id).innerHTML = 'Comenta esta lista';
	 }

	function setNumComentariosPortada(id) {
		var dir;
		if(id) {
			var http = createRequestObject();
			dir = baseurl+'backend/getcomentariosportada.php?id=' + id + '&by=date';
			http.open('get', dir);
			http.onreadystatechange = function () {
			if(http.readyState == 4) {
				if(http.responseText) {
					var campos = http.responseText.split('|');
					var limite = campos.length;
					var i = limite - 1;
					do {
						campos2 = campos[i].split('@');
						var num = campos2[1];
						switch (num) {
							case '0':
								if(window.document.getElementById('num-comentarios-' + campos2[0])) window.document.getElementById('num-comentarios-' + campos2[0]).innerHTML = 'Comenta esta lista';
								break;
							case '1':
								if(window.document.getElementById('num-comentarios-' + campos2[0])) window.document.getElementById('num-comentarios-' + campos2[0]).innerHTML = '<strong>' + num + '</strong> Comentario';
								break;
							default:
								if(window.document.getElementById('num-comentarios-' + campos2[0])) window.document.getElementById('num-comentarios-' + campos2[0]).innerHTML = '<strong>' + num + '</strong> Comentarios';
								break;
							}
						}
						while (i--);
					}
				}
			};
			http.send(null);
		}
	}

	function getComentarios(id, by) {
		var dir;
		if(id) {
			var http = createRequestObject();
			dir = baseurl+'backend/getcomentarios.php?id=' + id + '&by=' + by + '&r=' + Math.random();
			http.open('get', dir); 
			http.onreadystatechange = function () {
				if(http.readyState == 4) {
					if(http.responseXML) {
						if (http.responseText.indexOf('comments') != -1) {
							muestraComentarios(http.responseXML);
							window.document.getElementById('lomasreciente').className = (by == 'date') ? 'activo' : '';
							window.document.getElementById('lomasvalorado').className = (by == 'votes') ? 'activo' : '';
						}
					}
				}
			};
			http.send(null);
		}
	}

	function muestraComentarios(response, pagina) {
		var contenido;
		var html;
		var fecha_load = new Date();
		var browser = navigator.appName;
		var positive_votes;
		var negative_votes;
		var max_comentarios = 5;
		pagina = typeof(pagina) != 'undefined' ? pagina : 1;
		var limite = response.getElementsByTagName('comment').length;
		var num_comentarios = response.getElementsByTagName('total_comments')[0].firstChild.data;
		html = '<h6 class="num_opiniones">' + num_comentarios + ' OPINIONES</h6>';
		html += '<div id="bloque-opiniones">';

		var limite_b = ((((pagina - 1) * max_comentarios) + max_comentarios) > limite) ? limite : (((pagina - 1) * max_comentarios) + max_comentarios);
		var inicio = (pagina - 1) * max_comentarios;
		var paginas = Math.ceil(limite / max_comentarios);
		var pagina_ver = (pagina < 10) ? '0' + pagina : pagina;
		var paginas_ver = (paginas < 10) ? '0' + paginas : paginas;
		for(var i = inicio; i < limite_b; i++) {
			var id = response.getElementsByTagName('id')[i].firstChild.data;
			var fecha = response.getElementsByTagName('date')[i].firstChild.data;
			var campos = fecha.split(' ');
			var hora = campos[3];
			fecha = campos[2] + "/" + campos[1] + "/" + campos[5];
			/*
			var fecha = response.getElementsByTagName('date')[i].firstChild.data;
			var hora = fecha.substr(8,2) + ':' + fecha.substr(10,2)
			*/
			var nombre = response.getElementsByTagName('name')[i].firstChild ? response.getElementsByTagName('name')[i].firstChild.data : '';
			var mi_url = window.document.location.href;
			if(mi_url.indexOf('abc.es') > 0){
				var datos_nombre = nombre.split('||');
			}
			var texto = (browser == 'Microsoft Internet Explorer') ? response.getElementsByTagName('content')[i].firstChild.data : response.getElementsByTagName('content')[i].childNodes[1].data;
			positive_votes = response.getElementsByTagName('positive_votes')[i].firstChild.data;
			negative_votes = response.getElementsByTagName('negative_votes')[i].firstChild.data;
			// fecha = fecha.substr(6,2) + "/" + fecha.substr(4,2) + "/" + fecha.substr(0,4);
			contenido = '<div class="opinion">';
			contenido += '<div class="fecha">' + fecha + ' | <span class="hora">' + hora + '</span></div>';
			contenido += '<h4 class="autor">' + unescape(nombre) + '</h4>';
			contenido += '<br class="clear"/>';
			contenido += '<p class="texto">' + unescape(texto) + '</p>';

			contenido += '<div class="detalles-opinion">';
			contenido += '<div class="favorcontra" id="favorcontra-' + id + '">';
			contenido += '<a href="javascript:votarComentario(' + id+ ', 1);" class="afavor">A favor (' + positive_votes + ')</a>';
			contenido += '<a href="javascript:votarComentario(' + id + ', 2);" class="encontra">En contra (' + negative_votes + ')</a>';
			contenido += '</div>';
			contenido += '<a href="javascript:mostrarDenunciar(' + id + ');" id="inadecuadoboton" class="inadecuado boton" title="Comentario inadecuado"><img src="http://www.lavozdigital.es/img/ico_inadecuado.gif" alt="Comentario inadecuado" />Comentario inadecuado</a>';
			contenido += '<div class="clear"></div>';
			contenido += '</div>';

			contenido += '<div class="formdenunciar" id="formdenunciar-' + id + '" style="display:none;">';
			contenido += '<form name="formulario_' + id + '" action="/listas/backend/denunciarcomentario.php" method="post">';
			contenido += '<input type="hidden" name="load_time" value="' + fecha_load.getTime() + '">';
			contenido += '<input type="hidden" name="submit_time" value="0">';
			contenido += '<input type="hidden" name="id" value="' + id + '">';
			contenido += '<input type="hidden" name="anchor" value="comentarios">';
			contenido += '<p>Por favor seleciona el motivo por el que crees que este comentario es inadecuado </p>';
			contenido += '<textarea name="denuncia">Escriba aquí el motivo de la denuncia.</textarea>';
			contenido += '<a href="javascript:denunciarComentario(' + id + ');" class="boton">denunciar comentario</a>';
			contenido += '<div class="clear"></div>';
			contenido += '</form>';
			contenido += '<div class="clear"></div>';
			contenido += '</div>';
			
			contenido += '</div>';
			html += contenido;
		}
		html += '</div>';
		if(limite > max_comentarios) {
			html += '<div class="botones_listado"><a id="anterior" href="javascript:nada()" class="boton anterior">&lt;&lt;';
			html += 'Anterior</a>&nbsp;&nbsp;<span><strong>' + pagina_ver + '</strong>/' + paginas_ver + '</span>&nbsp;&nbsp;<a id="siguiente" href="javascript:nada()" class="boton siguiente">Siguiente';
			html += '&gt;&gt; </a></div>';
		}
		window.document.getElementById('listado-comentarios').innerHTML = html;
		window.document.getElementById('num-comentarios').innerHTML = num_comentarios;
		if(limite > max_comentarios) {
			window.document.getElementById('anterior').onclick = function () {
				if (pagina != 1) {
					muestraComentarios(response, (pagina - 1));
				}
				else {
					muestraComentarios(response, pagina);
				}
			}
			window.document.getElementById('siguiente').onclick = function () {
				if (pagina != paginas) {
					muestraComentarios(response, (pagina + 1));
				}
				else {
					muestraComentarios(response, pagina);
				}
			}
		}
	}

	function enviaComentario() {
		var fecha_submit = new Date();
		if(window.document.formulario.author_name.value == '') {
			alert('Por favor, introduce tu nombre');
			window.document.formulario.author_name.focus();
			return;
		}
		if(window.document.formulario.author_email.value == '') {
			alert('Por favor, introduce tu email');
			window.document.formulario.author_email.focus();
			return;
		}
		if(window.document.formulario.message.value == '') {
			alert('Por favor, introduce tu opinión');
			window.document.formulario.message.focus();
			return;
		}
		if(!window.document.formulario.acepto.checked) {
			alert('Tienes que aceptar las condiciones de uso');
			return;
		}
		var registrado = getCookie('registrado') ? ' (Usuario registrado)' : '';
		window.document.formulario.message.value = window.document.formulario.message.value;
		window.document.formulario.author_name.value = window.document.formulario.author_name.value + registrado;
		window.document.formulario.submit_time.value = fecha_submit.getTime();
		window.document.formulario.submit();
		alert('Gracias por escribir un comentario');
	}

	function votarComentario(id, tipo) {
		var dir;
		if(id) {
			var http = createRequestObject();
			dir = baseurl+'backend/votarcomentario.php?id=' + id + '&tipo=' + tipo + '&r=' + Math.random();
			http.open('get', dir); 
			http.onreadystatechange = function () {
				if(http.readyState == 4) {
					if(http.responseText) {
						var response = http.responseText;
						if(response.indexOf('ok') != -1) {
							window.document.getElementById('favorcontra-' + id).innerHTML = (tipo == 1) ? '<span class="afavor">A favor</span> <span class="mensaje">| Gracias por votar</span>' : '<span class="encontra">En contra</span> <span class="mensaje">| Gracias por votar</span>';
						}
					}
				}
			};
			http.send(null);
		}
	}

	function mostrarDenunciar(id) {
		var display = window.document.getElementById('formdenunciar-' + id).style.display;
		if (display == 'none' && !getCookie('queid_log')) {
			alert('Para denunciar un comentario Regístrate');
			return;
		}
		window.document.getElementById('formdenunciar-' + id).style.display = (display == 'none') ? 'block' : 'none';
	}

	function denunciarComentario(id) {
		var fecha_submit = new Date();
		eval('var formu = window.document.formulario_' + id);
		formu.submit_time.value = fecha_submit.getTime();
		formu.submit();
		alert('Gracias por denunciar el comentario');
	}

	function muestraLogueo() {
		window.document.getElementById('artlogeo').style.display = '';
	}

	function borrarTexto() {
		if(window.document.formulario.message.value == 'escribe aquí tu comentario') {
			window.document.formulario.message.value = '';
		}
	}

	/***************************** FIN Comentarios **********************************/
