//par de funciones ajax
var isIE = false;
var req;
var destinoLayer = "";
var peticionActiva = false;

function callAjaxXML(url, destino) {

	if(!peticionActiva){
		peticionActiva = true;

		destinoLayer = destino;
		//	Primero vamos a ver si la URL es una URL :)
		if(url==''){
			return;
		}	
		
		//	Usuario inteligente...
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			req.onreadystatechange = processReception;			
			req.open("GET", url, true);
			req.send(null);
		//	...y usuario de Internet Explorer Windows
	    } else 
	    	if (window.ActiveXObject) {
			try {
	            req = new ActiveXObject("Msxml2.XMLHTTP");
	         } catch (e) {
	            try {
	               req = new ActiveXObject("Microsoft.XMLHTTP"); 
	            } catch (e) {}
	         }
			 
	        if (req) {
				req.onreadystatechange = processReception;
			    req.open('POST', url, true);
				req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				req.send();
	        }
	    }
		
	}else{
		alert('Tiene una petición en curso, espere a que termine');
	}
}

function processReception(){
	
	var detalles = document.getElementById(destinoLayer);
	
	if(req.readyState == 4){	
		
			detalles.innerHTML = req.responseText;
			
			//si hay alguna funcion javascript despues de la llamada la ejecuta
			var x = detalles.getElementsByTagName("script");
			
			for( var i=0; i < x.length; i++) {
				try{
					
					eval(x[i].text);
				}catch(exception){
					
				}
			}
			
			peticionActiva = false;
			
	} else {

			detalles.innerHTML = '<div class="cargando"><div>';
	}
}

function cargaFormu(urlDestino){	



	var name = document.frmCommentform.nombre;
	
	var campos = ''	
	+ 'pais=' + encodeURIComponent(document.frmCommentform.pais.value) +'&'
	+ 'aplicacion=' + encodeURIComponent(document.frmCommentform.aplicacion.value)+'&'
	+ 'seccion=' + encodeURIComponent(document.frmCommentform.seccion.value)+'&'
	+ 'nodo=' + encodeURIComponent(document.frmCommentform.nodo.value)+'&'
	+ 'descripcionNodo=' + encodeURIComponent(document.frmCommentform.descripcionNodo.value);
	if (name != null){
		campos = campos + '&nombre=' + encodeURIComponent(document.frmCommentform.nombre.value)+'&'
		+ 'email=' + encodeURIComponent(document.frmCommentform.email.value)+'&'
		+ 'web=' + encodeURIComponent(document.frmCommentform.web.value);
	}
	campos = campos + '&captcha=' + document.frmCommentform.captcha.value+'&'
	+ 'comentario=' + encodeURIComponent(document.frmCommentform.comentario.value)+'&'	
	+ 'url='+ window.location+'&'
	+ 'fecha=' + (new Date().getTime());
	try {
		campos = campos +'&'
	+ 'userTicket=' + document.frmCommentform.ticketUser.value+'&'
	+ 'ticket=' + document.frmCommentform.ticket.value;
		if (document.frmCommentform.ticketUser.value != ''){
			compCampos(true);
		}
	}catch(exception){
		compCampos(false);
	}
	
	callAjaxXML(urlDestino+'?'+campos, "divComentarios");

	
	
				
}

function cargaFormuAp(urlDestino,user){	

		var campos = '' 	
		+ 'nombrePais=' + encodeURIComponent(document.frmCommentform.nombrePais.value) +'&'
		+ 'tituloAplicacion=' +  encodeURIComponent(document.frmCommentform.tituloAplicacion.value)+'&'
		+ 'tituloSeccion=' +  encodeURIComponent(document.frmCommentform.tituloSeccion.value)+'&'
		+ 'tituloNodo=' +  encodeURIComponent(document.frmCommentform.tituloNodo.value)+'&'
		if (!user){
			campos = campos + 'nombre=' + encodeURIComponent(document.getElementById('nombre').value)+'&'
			+ 'email=' + document.getElementById('email').value+'&'
			+ 'web=' + document.getElementById('web').value+'&'
		}
		campos = campos + 'captcha=' + document.frmCommentform.captcha.value+'&'
		+ 'comentario=' + encodeURIComponent(document.getElementById('comentario').value)+'&'	
		+ 'fecha=' + (new Date().getTime());
	
		
		callAjaxXML(urlDestino+'?'+campos, "divComentarios");
		document.location = '#foco';
}

function cargaFormuEstDerech(urlDestino){	
		
		var campos = '' 	
		+ 'paisKey=' + document.frmEstadisticas.paisKey.value +'&'
		+ 'tituloAp=' + document.frmEstadisticas.tituloAp.value+'&'
		+ 'tituloSec=' + document.frmEstadisticas.tituloSec.value+'&'	
		+ 'fecha=' + (new Date().getTime());

		
		callAjaxXML(urlDestino+'?'+campos, "estadisDerech");
			
}



//funcion para recargar la imÃ¡gen del Captcha
function reloadImage() {
	var fecha = new Date().getTime();	
	var urlfinal = 'url('+urlServer+'Captcha.jpg?fecha='+ fecha+')';
 	document.getElementById('secureimgdiv').style.background = urlfinal;
}


//funcion para validar campos

function compCampos(userSession){

	var errores = false;
	var name =document.getElementById("nombre");
	if (!userSession && name != null){
		//mail
		var check = validaEmail(document.getElementById("email"));	
		cambiaBorde(check, document.getElementById("email"));	
		cambiaImg(check, document.getElementById("imgMail"));
		if(!check){errores = true;}
		//nombre
		check = validaBlanco(document.getElementById("nombre"))
		cambiaBorde(check, document.getElementById("nombre"));
		cambiaImg(check, document.getElementById("imgNombre"));			
		if(!check){errores = true;}
	}
	//captcha
	check = validaLongitud(document.getElementById("captcha"),5)		
	cambiaBorde(check, document.getElementById("captcha"));
	cambiaImg(check, document.getElementById("imgCaptcha"));
	if(!check){errores = true;}
	//comentario
	check = validaBlanco(document.getElementById("comentario"))
	cambiaBorde(check, document.getElementById("comentario"));	
	if(!check){errores = true;}
	
	if(errores==false){
		displayChange('submit', true);
	}else{
		displayChange('submit', false);
	}			
}

//recarga y borra los campos que necesita
function recargaPagina(){
	
	var name = document.frmCommentform.nombre;
	
	if (name != null){
		document.frmCommentform.nombre.value="";
		document.frmCommentform.email.value="";
		document.frmCommentform.web.value="";
	}
	document.frmCommentform.captcha.value="";
	document.frmCommentform.comentario.value="";
	document.location.reload(true);		
}

// Funcion para validar Email
function validaEmail(valor)
{    
  var pattern=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return pattern.test(valor.value);
}

// Funcion para cambiar de imÃ¡gen de error
function cambiaImg(key,img)
{	
	//img.src='../img/incorrecto.gif';
	if (key ==true)// 1 es correcto y 0 incorrecto
	{
		img.style.backgroundPosition = '0px -17px';
	}
	else
	{
		img.style.backgroundPosition = '0px 0px';
	}
}
// FunciÃ³n para cambiar el borde de color
function cambiaBorde(key, layer_ref){
	elem = document.getElementById(layer_ref);
	if (key ==true)// 1 es correcto y 0 incorrecto
	{
		layer_ref.style.borderColor = '#CCCCCC';
		layer_ref.style.borderStyle = 'solid';
	}
	else
	{
		layer_ref.style.borderColor = '#cc4444';
		layer_ref.style.borderStyle = 'dotted';
	}	 
}


//Funcion para comprobar que la logitud del campo sea la correcta
function validaLongitud(valor, longitud){
	t = Trim(valor.value);// primero le quita los espacios en blanco y despues comprueba
	if(t==null || t=="" || t.length != longitud){
		return false;
	}else{
		return true;
	}
}


// Funcion que devuelve false si el campo esta en blanco.
function validaBlanco(valor){
	t = Trim(valor.value);// primero le quita los espacios en blanco y despues comprueba
	if(t==null || t==""){
		return false;
	}else{
		return true;
	}
}

// Funciones Trim Retorna string con blancos quitados
function LTrim(str) {
	for (var i=0; str.charAt(i)==" "; i++);
	return str.substring(i,str.length);
}// los quita a la izquierda
function RTrim(str) {
	for (var i=str.length-1; str.charAt(i)==" "; i--);
	return str.substring(0,i+1);
}// los quita a la derecha
function Trim(str) {
	return LTrim(RTrim(str));
}// los quita a ambos lado


//muestra u oculta(true o flase) una capa indicada en layer_ref, 
function displayChange(layer_ref, state) {  
  if(state){
    newState = 'inline'; 
  }else{
    newState = 'none';
  }     

  if (document.all) { //IS IE 4 or 5 (or 6 beta)
    eval( "document.all." + layer_ref + ".style.display = newState");
  }
  if (document.layers) { //IS NETSCAPE 4 or below
    document.layers[layer_ref].display = newState;
  }
  if (document.getElementById && !document.all) {
    maxwell_smart = document.getElementById(layer_ref);
    maxwell_smart.style.display = newState;
  }          
}

//funcion que limita el mÃ¡ximo de longitud del campo comentario y devuelve los caracteres que quedan
function calcuLong(org, dst, maximo)
{
	if(org.value.length > maximo){
		org.value = org.value.substring(0,maximo);
	}
	dst.value = maximo-org.value.length;
	try{
		if (document.frmCommentform.ticketUser.value != '')
			compCampos(true);
		else
			compCampos(false);
	}catch(exception){
		compCampos(false);
	}
}

function calcuLong(org, dst, maximo, login)
{
	if(org.value.length > maximo){
		org.value = org.value.substring(0,maximo);
	}
	dst.value = maximo-org.value.length;
	compCampos(login);
}


//llamada a ajax para cargar la lista de acciones de la parte privada del usuario
function getActionsFrom (destino,div,action,first){
	vars = "action="+ action;
	vars = vars+ "&ticket="+ document.userFormViewActionList.ticket.value;
	vars = vars+ "&firstElement="+ first+ '&fecha=' + (new Date().getTime());
	
	/*START Nielsen//NetRatings Event Tracking function */
    _nnEventTrack('http://usuarios.universia.net/'+action);
     /*END Nielsen//NetRatings Event Tracking function*/
	
	
	callAjaxXML(destino+'/listaAcciones.action?'+vars, div);
}

//llamada a ajax para cargar la lista de acciones de la parte privada del usuario
function getActions (destino,div,action){
	
	getActionsFrom(destino,div,action,0);

}

//llamada a ajax para cargar la lista de acciones de la parte privada del usuario
function getActionsSize (destino,div,action){
	vars = "action="+ action;
	vars = vars+ "&login="+ document.userFormViewActionList.login.value;
	
	callAjaxXML(destino+'/numeroAcciones.action?'+vars, div);
	
}




//ESTRELLAS - funciones para la votacion del topico 
/* AJAX Star Rating : v1.0.3 : 2008/05/06 */
function $(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
function $S(o) { return((typeof(o)=='object'?o:$(o)).style); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function abPos(o) { var o=(typeof(o)=='object'?o:$(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.documentElement.scrollLeft,'Y':event.clientY+document.documentElement.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }

var mediaTexto=new Array("&nbsp;P&eacute;simo", "&nbsp;Muy Malo", "&nbsp;Malo", "&nbsp;Regular", "&nbsp;Bueno", "&nbsp;Muy Bueno", "&nbsp;Excelente");
var rutaTopico = '';

star={};

star.mouse=function(e,o) { if(star.stop || isNaN(star.stop)) { 
	star.stop=0;
	document.onmousemove=function(e) { var n=star.num;
	
		var p=abPos($('starCur'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);

		if(oX<1 || oX>99 || oY<0 || oY>19) { star.stop=1; star.revert(); }
		
		else {

			$S('starCur'+n).width=oX+'px';
			$S('starUser'+n).color='#111';
			$('starUser'+n).innerHTML=Math.round(oX/99*100)/10+' ';
			$('starTipo'+n).innerHTML=mediaTexto[Math.round((mediaTexto.length-1)*oX/100)];
      		
		}
	};
} };

star.update=function(e,o) { 
  var n=star.num, v=parseInt(($('starUser'+n).innerHTML)*10);

	n=o.id.substr(4); $('starCur'+n).title=v;
    
	$('star'+n).onmousemove = null;
	$('star'+n).onmousedown = null;
	
  	try{
  		var sending =  rutaTopico+ '&valorNuevoVoto=' + v +  '&pais=' + encodeURIComponent(document.frmCommentform.pais.value) +'&'
		+ 'aplicacion=' + encodeURIComponent(document.frmCommentform.aplicacion.value)+'&'
		+ 'seccion=' + encodeURIComponent(document.frmCommentform.seccion.value)+'&'
		+ 'nodo=' + encodeURIComponent(document.frmCommentform.nodo.value)+'&'+ 'url='+ window.location;
	try{
		sending = sending +'&'+'descripcionNodo=' +  encodeURIComponent(document.frmCommentform.descripcionNodo.value); 
	}catch(exception){}
	try{
		sending = sending +'&userTicket=' + document.frmCommentform.ticketUser.value+'&'
		+ 'ticket=' + document.frmCommentform.ticket.value; 
	}catch(exception){}
  		callAjaxXML( sending
  					, 'starMensaje0');
  		
  		
		//$('starMensaje'+n).innerHTML="Gracias por su voto";
	}catch(err){
		$('starMensaje'+n).innerHTML="Se produjo un error. Sentimos las molestias.";
	}  	

};

star.revert=function() { 
	  var n=star.num, v=parseInt($('starCur'+n).title);		
		$S('starCur'+n).width=Math.round(v*99/100)+'px';
		$('starUser'+n).innerHTML=(v>0?Math.round(v)/10+' ':' ');
		var auxTexto = '';
		if(v!=0){
			auxTexto = mediaTexto[Math.round((mediaTexto.length-1)*v/100)];
		}
		$('starTipo'+n).innerHTML=auxTexto;
			
		document.onmousemove='';
};


star.show = function(nId, pMedia, numVotos, urlTopico){  
	
  	pMedia = (Math.round(pMedia*10))/10;
  	v=parseInt(pMedia*10);
  	  
	$S('starCur'+nId).width=Math.round(v*99/100)+'px';
	$('starUser'+nId).innerHTML=(v>0?Math.round(v*10)/100+' ':'');
  	$('starCur'+nId).title=v;
  	$('star'+nId).style.display = 'inline';

  	$('starMensaje'+nId).innerHTML="<b>Votos totales:</b>&nbsp;"+numVotos+"&nbsp;<b>Puntuaci&oacute;n media:</b>&nbsp;"+pMedia; 
	if(numVotos>0){
		$('starTipo'+nId).innerHTML=mediaTexto[Math.round((mediaTexto.length-1)*v/100)];
	}
  
  	rutaTopico = urlTopico;       	        	
};

star.num=0;


/*START Nielsen//NetRatings Event Tracking function */
/* COPYRIGHT 2006 Nielsen//NetRatings */
function _nnEventTrack(_nnClickURL){
	var _nnCI = "es-universia";
	var _nnCG = "0";
	var _nnCC = "uk"; /* country code */
	var _nnLP = location.protocol.indexOf('https')>-1?'https:':'http:';
	var _nnRP = escape(window.location);
	var _nnND = _nnLP + '//secure-' + _nnCC + '.imrworldwide.com/';
	var _nnPixel = new Image(1,1);
	var _nnParams = "rnd=" + (new Date()).getTime() + "&ci=" + _nnCI + "&cg=" + _nnCG;
	_nnParams += "&si=" + escape(_nnClickURL) + "&rp=" + _nnRP;
	_nnPixel.src = _nnND + "cgi-bin/m?" + _nnParams;
}

/*END Nielsen//NetRatings Event Tracking function*/



