//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++) {
			  eval(x[i].text);
			}
			peticionActiva = false; 
	} else {

			detalles.innerHTML = '<div class="cargando"><div>';
	}
}

function cargaFormu(urlDestino){	

	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)+'&'
	+ 'nombre=' + encodeURIComponent(document.frmCommentform.nombre.value)+'&'
	+ 'email=' + encodeURIComponent(document.frmCommentform.email.value)+'&'
	+ 'web=' + encodeURIComponent(document.frmCommentform.web.value)+'&'
	+ 'captcha=' + document.frmCommentform.captcha.value+'&'
	+ 'comentario=' + encodeURIComponent(document.frmCommentform.comentario.value)+'&'	
	+ 'url='+ window.location+'&';
	+ 'fecha=' + (new Date().getTime());

	callAjaxXML(urlDestino+'?'+campos, "divComentarios");
	compCampos();
				
}

function cargaFormuAp(urlDestino){	
	
		var campos = '' 	
		+ 'nombrepais=' + encodeURIComponent(document.frmCommentform.nombrepais.value) +'&'
		+ 'tituloAp=' +  encodeURIComponent(document.frmCommentform.tituloAp.value)+'&'
		+ 'tituloSec=' +  encodeURIComponent(document.frmCommentform.tituloSec.value)+'&'
		+ 'tituloNodo=' +  encodeURIComponent(document.frmCommentform.tituloNodo.value)+'&'
		+ 'co.nombre=' + encodeURIComponent(document.getElementById('nombre').value)+'&'
		+ 'co.email=' + document.getElementById('email').value+'&'
		+ 'co.web=' + document.getElementById('web').value+'&'
		+ 'captcha=' + document.frmCommentform.captcha.value+'&'
		+ 'co.comentario=' + encodeURIComponent(document.getElementById('comentario').value)+'&'	
		+ 'fecha=' + (new Date().getTime());
	
		callAjaxXML(urlDestino+'?'+campos, "divComentarios");
		compCampos();	

}

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;
	compCampos();
}

//funcion para validar campos
function compCampos(){

	var errores = false;
	//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(){
	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;
	compCampos();
}


//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;Too Bad", "&nbsp;Bad", "&nbsp;Poor", "&nbsp;So so", "&nbsp;Good", "&nbsp;Very good", "&nbsp;Excellent");
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;
	
  	//req=new XMLHttpRequest(); req.open('GET','/AJAX_Star_Vote.php?vote='+(v/100),false); req.send(null);    	
  	try{
  		callAjaxXML(rutaTopico+ '&valorNuevoVoto=' + v, 'starMensaje0');
		//$('starMensaje'+n).innerHTML="Gracias por su voto";
	}catch(err){
		$('starMensaje'+n).innerHTML="Se produjo un error. Sentimos las moléstias.";
	}  	

};

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>Total rates:</b>&nbsp;"+numVotos+"&nbsp;<b>Average rating:</b>&nbsp;"+pMedia; 
	if(numVotos>0){
		$('starTipo'+nId).innerHTML=mediaTexto[Math.round((mediaTexto.length-1)*v/100)];
	}
  
  	rutaTopico = urlTopico;       	        	
};

star.num=0;