var invitado;
var active_search_id;
var imagen_videochat;
var feature_imagen_videochat;
var identificador_global;
var formulario;
var tipo_refresco;
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_1 ;
var http_2;
var http_3;
var http_4; // on/off imagen dinamica
function llamadaAjax(ident,url,arg,func)
{
	eval('http_'+ident+' = crearObjeto();');
	var randomnumber=Math.floor(Math.random()*1100)
	eval('http_'+ident+'.open(\'get\',url+\'&num=\'+randomnumber+\'&\'+arg,true);');
	eval("http_"+ident+".onreadystatechange = "+func+";");
	try { eval('http_'+ident+'.send(null);'); } catch(e) { alert('Se ha producido un error. Debe actualizar la página'); }
}	


function ready(identificador_ready,videochat_invitado_ready)
{
identificador_global =	identificador_ready;
invitado = videochat_invitado_ready;	
}

function start_search (identificador1,videochat_invitado,tipo_refresco)
{
identificador_global =	identificador1;
invitado = videochat_invitado;	
setInterval("comprueba()", 60000);                      // 10000
setInterval("comprueba_preg_pendientes()", 180000);     // 25000
	if (tipo_refresco=='imagen_dinamica') 
	{
		refresco_normal_start();
		setInterval("refresco_normal_start()", 25000);
	}
}


//----------------------------- FUNCTION SIMILAR A TRIM PARA ELIMINAR ESPACOS

function trim(cadena)
{
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	
	return (cadena);
}

// ----------------------------- FIN FUNCTION TRIM



//-----------------------------------------------	 FUNCIONES PARA EL ENVIO DE UNA PREGUNTA
function pinta_formulario ()
{
			document.getElementById("contenedora_formulario").innerHTML= formulario;
			
}
function envia_pregunta()		
{
	
	//formulario = document.getElementById("contenedora_formulario").innerHTML;
		
	formulario= 	"<h2><img alt=\"\" src=\"/smarty/templates/ozu/activo/images/carpeta.gif\" class=\"imagen1\" border=\"0\">									Haz tu pregunta							<div id=\"show_form_pregunta\" style=\"display: inline;\"></div>					</h2>					<div id=\"formulario_envio_pregunta\" style=\"display: inline;\">					<form method=\"post\" name=\"envio_postal_form\" id=\"envio_postal_form\" action=\"envio_pregunta.php\">					<fieldset style=\"border: 0pt none ; padding: 10px 0pt;\">						<input name=\"validar_pregunta\" value=\"1\" type=\"hidden\">					<input value=\"asdsadf\" name=\"famoso\" type=\"hidden\">				<div class=\"fila\">						<label><span>Nick:</span></label> <textarea id=\"nick_videochat\" cols=\"30\" rows=\"1\" name=\"nick_videochat\"></textarea>					</div>					<div class=\"fila\">						<label><span>Pregunta:</span></label><textarea id=\"pregunta_videochat\" rows=\"3\" cols=\"30\" name=\"pregunta_videochat\"></textarea>					</div>					<div class=\"fila\">						<a href=\"JavaScript:envia_pregunta()\">							<img alt=\"Enviar\" src=\"/smarty/templates/ozu/activo/images/enviar.gif\" class=\"enviar\" border=\"0\">						</a>						</div>					</fieldset>					</form></div>";
	var nick_usuario = document.getElementById('nick_videochat').value;	
  nick_usuario = nick_usuario.replace(/^(\s|\&nbsp;)*|(\s|\&nbsp;)*$/g,"");
 	
	var pregunta_usuario = document.getElementById('pregunta_videochat').value;	
	pregunta_usuario = pregunta_usuario.replace(/^(\s|\&nbsp;)*|(\s|\&nbsp;)*$/g,"");
 	
	
		if ((nick_usuario.length<=1)	|| (nick_usuario==null)|| (pregunta_usuario=="")|| (pregunta_usuario.length<=1))	
			{ 
			alert("Debes rellenar el formulario correctamente");
			}else
					{
					document.getElementById("contenedora_formulario").innerHTML="<img src='administracion/img/ajax-loader.gif' border='0'> Enviando su pregunta ...";
					llamadaAjax('3','envio_pregunta.php?videochat='+invitado+'&nick='+encodeURI(nick_usuario),'pregunta='+encodeURI(pregunta_usuario),'fin_envia_pregunta');
					}
}

function fin_envia_pregunta()
{
	if (http_3.readyState == 4 && (http_3.status==200 || window.location.href.indexOf("http")==-1)) 
	{
		txt = http_3.responseText;
					if ((txt!=""))
										{
										document.getElementById("contenedora_formulario").innerHTML="";		
										new Insertion.Top('contenedora_formulario',"<div class='form_pregunta_enviada_ok'>"+http_3.responseText+", Espere 10 segundos para enviar otra pregunta...</div>");
										setTimeout("pinta_formulario()", 10000);
										}
	}
}


///------ FUNCIONES PRINCIPALES DE REFRESCO Y ACTUALIZACION DE LAS PREGUNTAS RESPONDIDAS ----------
function comprueba()		
{

	llamadaAjax('1','active_search.php?videochat='+invitado,'position='+identificador_global,'devuelve_informacion_frontal');
}

function devuelve_informacion_frontal()
{
	if (http_1.readyState == 4 && (http_1.status==200 || window.location.href.indexOf("http")==-1)) 
	{
		var clase_pregunta='';
		var txt="";
		var i = 0;
		txt = http_1.responseText;
		var lineas = txt.split('$$');
		for(i = 0 ; i < lineas.length && lineas[i] != ''; i++)
		{
			txt = lineas[i].split("||");
			var ultimoposition 	= txt[0];
			var pregunta 				= txt[1];
			var nick 						= txt[2];
			var respuesta 			= txt[3];
			var tipo_pregunta		= txt[4];
			var div_id		= txt[5];
		  if ((pregunta != "undefined") && (pregunta != undefined) && (respuesta != "undefined") && (respuesta != undefined))
		  {	
				// Comprobar que estilo aplicar
				if (tipo_pregunta=='1')
				{
					clase_pregunta='linea_admin';
				}
				else
				{
						clase_pregunta='linea';
				}
			
				// Primero Probar si existe la posicion
				if (document.getElementById('linea_'+div_id))
				{
					//var check_linea = document.getElementById('linea_'+div_id).innerHTML = "<div class='"+clase_pregunta+"'><div class='pregunta'>"+pregunta+"("+nick+")</div><div class='respuesta'>"+respuesta+"</div></div>";
					//Effect.Pulsate('linea_'+div_id);
					identificador_global = ultimoposition;
				}	
		    else
		    { 
					// Insertar nueva preg/resp
					if ((respuesta!=""))
					{	
						new Insertion.Top('contenido', "<div id='linea_"+div_id+"' class='"+clase_pregunta+"'><div class='pregunta'>"+pregunta+"("+nick+")</div><div class='respuesta'>"+respuesta+"</div></div>");
						Effect.Pulsate('linea_'+div_id);
						identificador_global = ultimoposition;
					}
				}
			}
		}
	}
}

//----------------------------- FUNCIONES PARA ACTUALIZAR Y VISUALIZAR EL CONTENIDO DE LAS PREGUTNAS PENDIENTES ------------------

function comprueba_preg_pendientes()		
{	
	document.getElementById("preguntas_pendientes").innerHTML="<img src='administracion/img/ajax-loader.gif' border='0'> Actualizando Preguntas Pendientes ...";		
	llamadaAjax('2','active_search_pendientes.php?videochat='+invitado,'actividad=1','devuelve_preg_pendientes');
}

function devuelve_preg_pendientes()
{
	if (http_2.readyState == 4 && (http_2.status==200 || window.location.href.indexOf("http")==-1)) 
	
	{
		document.getElementById("preguntas_pendientes").innerHTML="";
		new Insertion.Top('preguntas_pendientes', '<h2>Preguntas pendientes</h2><div class="comentarios">'+ http_2.responseText+'</div>');
		//Effect.Pulsate('preguntas_pendientes');		
		
	}
}


// ---------------------------- FUNCIONES PARA ACTIVAR/DESACTIVAR WEBCAM REFRESCO NORMAL 
function refrescaImagen()
										{
											var aleat = Math.random() * 10000000;
										  aleat = Math.floor(aleat);
											document.getElementById('img_videochat').src = 'http://vchat.advernet.es/'+imagen_videochat+'.jpg?'+aleat;
										}
function refresco_normal_start()
{
	imagen_videochat = invitado;
	llamadaAjax('4','busqueda_emitiendo_webcam.php?videochat='+invitado,'actividad=1','refresco_normal_start_ok');
}

function refresco_normal_start_ok()
{	
	if (http_4.readyState == 4 && (http_4.status==200 || window.location.href.indexOf("http")==-1)) 
	{
		if (http_4.responseText==1)
		{	
			document.getElementById('webcam_imagen_dinamica').style.display = 'inline';	
			document.getElementById('foto_imagen_dinamica').style.display = 'none';	
			document.getElementById('tr_parar_videochat').style.display = 'none';	
			document.getElementById('tr_comenzar_videochat').style.display = 'none'; 
            if (feature_imagen_videochat > 0)
            {
                clearInterval(feature_imagen_videochat);
            }
			feature_imagen_videochat =	setInterval("refrescaImagen()",20000);
		}else{
					if (feature_imagen_videochat > 0)
					{
						setTimeout("clearInterval("+feature_imagen_videochat+")",2000);
					}
					document.getElementById('webcam_imagen_dinamica').style.display = 'none';	
					document.getElementById('foto_imagen_dinamica').style.display = 'inline';
					document.getElementById('tr_parar_videochat').style.display = 'none';	
					document.getElementById('tr_comenzar_videochat').style.display = 'inline';			 		 
				 }
		
		}
}

///----------------- funciones para mostar biografia

function mostrar_biografia()
{
	Effect.SlideDown('biografia');
	document.getElementById('show_bio').style.display = 'none';	
	document.getElementById('hide_bio').style.display = 'inline';
}
function ocultar_biografia()
{
	Effect.SlideUp('biografia');
	document.getElementById('show_bio').style.display = 'inline';	
	document.getElementById('hide_bio').style.display = 'none';
}

//-------------------- funciones para mostrar formulario enviar pregunta

function mostrar_pregunta_form()
{
 Effect.SlideDown('formulario_envio_pregunta');
 document.getElementById('show_form_pregunta').style.display = 'none';
 document.getElementById('hide_form_pregunta').style.display = 'inline';
}

function ocultar_pregunta_form()
{
 Effect.SlideUp('formulario_envio_pregunta');
 document.getElementById('show_form_pregunta').style.display = 'inline';
 document.getElementById('hide_form_pregunta').style.display = 'none';	
}



function abrir_videochat()
{
var destino;
destino= document.getElementById('abrir_videochat_blank').value;
document.getElementById('invitados').action= destino;
document.invitados.submit();	
}