//MENSAJES
var msj1="Your email address in invalid";
var msj2="You must sign in to leave a comment";
var msj3="Please enter a comment";
var msj4="The newsletter subscription is confirmed";
var msj5="This email has already been registred";
var msj6="Please enter you email and Password";
//var msj7="Invalid data";
var msj8="Insufficient credit";
var msj9="This email has already been registered";
var msj10="Thank you for leaving a comment";
var msj11="Do you want to remove this resource from your favourites?";
var msj12="Do you want to add this resource to your favorites?";

var url_site = document.location.href
var url_pos=url_site.indexOf('//');
var url_limpia = url_site.substr(url_pos+2);
var url_prot= url_site.substr(0,url_pos+2);
var url_split= url_limpia.split('/');
//var domain_name= url_prot + url_split[0];

var bReloadAfterLogin=0;	//Variable para indicar si hay que recargar la pagina al hacer login

var nav4 = window.Event ? true : false;	
function solonumeros(evt)
{
// Backspace = 8, Enter = 13, ‘0' = 48, ‘9' = 57, ‘.’ = 46
if (window.event)
	{var key = window.event.keyCode;}
else
	{var key = nav4 ? evt.which : evt.keyCode;}
return (key <= 13 || (key >= 48 && key <= 57) || key == 44 || key == 45);
}

/*** Imagenes ***/
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function cambiaclase(x,tipo,y)
{	
var control='div'+x
if(y==1)
	{
	var c1='detalles2_b';
	var c2='detalles_b';
	}
if(y==2)
	{
	var c1='detalles2_c';
	var c2='detalles_c';
	}
if(!y)
	{
	var c1='detalles2';
	var c2='detalles';
	}
if(tipo==2)
	{
	document.getElementById(control).className=c1;
	}
else
	{
	document.getElementById(control).className=c2;	
	}
}
/***ajax*///
function getHTTPObject()
{
 var xmlhttp = null;
 //Internet Explorer
 try
 {
  xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
 }
 catch (e)
 {
  try
  {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch (e)
  {
   xmlhttp = null;
  }
 }

 //Mozilla y Safari

 if ((xmlhttp == null) && (typeof XMLHttpRequest != 'undefined'))
 {
  try
  {
   xmlhttp = new XMLHttpRequest();
  }
  catch (e)
  {
   xmlhttp = null;
  }
 }
 return xmlhttp;
}
var enProceso = false; // lo usamos para ver si hay un proceso activo
var http =  getHTTPObject(); // Creamos el objeto XMLHttpRequest
function comentar(id,usu,tipo)
{
if(usu==0)
	{
	alert(msj2);
	}
else
	{
	if(document.getElementById('comentarios').value=='')
		{
		alert(msj3);
		}
	else
		{
		if (!enProceso && http) 
			{
			var url = "app/includes/consultas_ajax_front.php?comando=comentario&recurso="+id+"&comen="+document.getElementById('comentarios').value+"&tipo="+tipo;
			http.open("GET", url, true);
			http.onreadystatechange = comentario_cmd;
			enProceso = true;
			http.send(null);
			}
		}
	}
}
function comentario_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
						var valores= http.responseText;
						enProceso = false;
						document.getElementById('comentarios').value='';
						alert(valores);			
          }
       }
    }
}
function quit_favoritos(id)
{
var x=confirm(msj11);
if(x)
	{
	window.open("includes/inserciones.php?pag=miportal.php?men=4&accion=quit_favoritos&recurso="+id, "_parent");
	}
}
function add_favoritos(id)
{
var x=confirm(msj12);
if(x)
	{
	if (!enProceso && http) 
		{
		var url = "app/includes/consultas_ajax_front.php?comando=add_favoritos&recurso="+id;
		http.open("GET", url, true);
		http.onreadystatechange = favoritos_cmd;
		enProceso = true;
		http.send(null);
		}
	}
}
function favoritos_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
						var valores= http.responseText;
						enProceso = false;			
          }
       }
    }
}

function busca_duplicado_news(comando,modulo,valor)
{
	var urlLocal = "includes/consultas_ajax.php?comando="+comando+"&modulo="+modulo+"&valor="+valor;	
	http.open("GET", urlLocal, false);
  http.send(null);
  if (http.responseText==0){  
  	 urlLocal = "includes/inserciones_ajax.php?comando="+comando+"&modulo="+modulo+"&valor="+valor;
 		 http.open("GET", urlLocal, false);
 		 http.send(null);
 		 alert(msj4);
  }else{
  	alert(msj5);
  }
}
function busca_duplicado_cliente(comando,modulo,valor)
{	
	var urlLocal = "includes/consultas_ajax.php?comando=add&modulo=registro&valor="+document.getElementById('commentForm').email.value;
	http.open("GET", urlLocal, false);
  http.send(null);
  
 if (http.responseText==0){
  	 return true;  	 
  }
  return false;
}

function pass_ok(pass)
{
	
	var urlLocal = "includes/consultas_ajax.php?comando=add&modulo=compruebapass&valor="+pass;
	
	http.open("GET", urlLocal, false);
  http.send(null);
  
 if (http.responseText==1){
  	 return true;
  	 
  }
  return false;
}

//JF
function clearForm(form) {		
  // iterate over all of the inputs for the form
  // element that was passed in
  $(':input', form).each(function() {	  	
		 var type = this.type;
		 var tag = this.tagName.toLowerCase(); // normalize case
		 // it's ok to reset the value attr of text inputs,
		 // password inputs, and textareas
		 if (type == 'text' || type == 'password' || tag == 'textarea')			 
		 	this.value="";			 	
		 // checkboxes and radios need to have their checked state cleared
		 // but should *not* have their 'value' changed
		 else if (type == 'checkbox' || type == 'radio')
		   this.checked = false;
		 // select elements need to have their 'selectedIndex' property set to -1
		 // (this works for both single and multiple select elements)
		 else if (tag == 'select')
		   this.selectedIndex = 0;
	});
};
var subtipo=0; var costo=0;var tipo=0; var abierto=0;verinfografia=0;
function check_download(subt,cost,tip,abiert,verinfo)
{
abierto=abiert;
subtipo=subt
costo=cost;
tipo=tip;
verinfografia=verinfo;
if (!enProceso && http) 
		{
		var url = "app/includes/consultas_ajax_front.php?comando=check_download&tipo="+tipo+"&abierto="+abierto+"&verinfografia="+verinfografia;
		http.open("GET", url, true);
		http.onreadystatechange = checkdownload_cmd;
		enProceso = true;
		http.send(null);
		}
}
var sinlimite=0;
function checkdownload_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
			var valores= http.responseText;
			valores=valores.split("|");
			enProceso = false;
			document.getElementById('txt_saldo').value=valores[5];
			sinlimite=valores[2];
			if(valores[0]==0)
				{
				download();
				}
			else
				{
				if(valores[1]==3)
					{
					window.open($("base").attr("href")+'htmltopdf.php', '_parent');		
					}
				else
					{
					if(valores[3]==1)
						{
						window.open($("base").attr("href")+valores[4], '_blank');		
						}
					else
						{
						if((tipo==4)&(verinfografia==1))
							{								
							$(document).ready(function(){
							$("a#caja_loading").trigger("click");
							});
							}
						else
							{
							window.open($("base").attr("href")+'includes/download.php', '_parent');		
							}
						}
					}
				}
          }
       }
    }
}
function download()
{
var saldo=document.getElementById('txt_saldo').value;
if((saldo<costo)&&(sinlimite==0)&&(tipo!=3))
	{
	alert(msj8);
	}
else
	{
		if (!enProceso && http) 
			{
			var url = "app/includes/consultas_ajax_front.php?comando=download&recid=1&subtipo="+subtipo+"&tipo="+tipo+"&abierto="+abierto+"&sinlimite="+sinlimite+"&verinfografia="+verinfografia;			
			http.open("GET", url, true);
			http.onreadystatechange = download_cmd;
			enProceso = true;
			http.send(null);
			}		
	}
}
function download_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
			var valores= http.responseText;
			valores=valores.split("|");
			enProceso = false;
			document.getElementById('txt_saldo').value=valores[1];
			if(valores[0]==3)
				{
				window.open($("base").attr("href")+'htmltopdf.php', '_parent');		
				}
			else
				{
				//en el caso de que sea un audio con link
				if(valores[2]==1)
					{
					window.open(valores[3], '_blank');
					}
				else
					{
					if((tipo==4)&(verinfografia==1))
						{						
						$(document).ready(function(){
						$("a#caja_loading").trigger("click");
						});
						}
					else
						{
						window.open($("base").attr("href")+'includes/download.php', '_parent');		
						}
					}
				}
          }
       }
    }
}
var tipo=0;file='';baseurl='';costo=0;
function check_streaming(fil,base,tip,cost,abiert)
{
abierto=abiert;
tipo=tip
file=fil;
baseurl=base;	
costo=cost;
if (!enProceso && http) 
		{
		var url = "app/includes/consultas_ajax_front.php?comando=check_streaming&tipo="+tipo+"&abierto="+abierto;
		http.open("GET", url, true);
		http.onreadystatechange = checkstreaming_cmd;
		enProceso = true;
		http.send(null);
		}
}
var cont='';
function checkstreaming_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
			var valores= http.responseText;
			valores=valores.split("|");
			enProceso = false;
			document.getElementById('txt_saldo').value=valores[1];
			costo=valores[2];
			baseurl=valores[3];	
			if(valores[0]==0)
				{
				streaming();
				}
			else
				{
				if((tipo==1)|(tipo==4))
					{
					if(tipo==1)
						{
							//if (window.console && window.console.firebug){ console.debug(baseurl); }
							$(document).ready(function(){
								$("a#caja_loading").trigger("click");
								$('#loading').flash({swf:file,height:420, width:700, wmode: 'transparent', base:baseurl});
							});
						}
					else
						{
						$(document).ready(function(){
						$("a#caja_loading").trigger("click");
						});	
						}						
					}
				else
					{
					cont=document.getElementById('cont').innerHTML;
					flowplayer("div.player","app/includes/flowplayer/flowplayer-3.2.7.swf");
					flowplayer("div.player",{src:"app/includes/flowplayer/flowplayer-3.2.7.swf", wmode:"opaque"},{clip:{autoPlay: true,autoBuffering: true},playlist: [{baseUrl: $("base").attr("href"),url: 'app/includes/view_video.php'}],onFinish: function() {clear_video();}});					
					}
				}
          }
       }
    }
}

function clear_video()
{
document.getElementById('cont').innerHTML='';
document.getElementById('cont').innerHTML=cont;
}

		
function streaming()
{
var saldo=document.getElementById('txt_saldo').value;
if((saldo<costo)&&(abierto==0))
	{
	alert(msj8);
	}
else
	{	
	if (!enProceso && http) 
		{
		var url = "app/includes/consultas_ajax_front.php?comando=streaming&tipo="+tipo+"&saldo="+saldo+"&costo="+costo+"&abierto="+abierto;		
		http.open("GET", url, true);
		http.onreadystatechange = streaming_cmd;
		enProceso = true;
		http.send(null);
		}		
	}
}
function streaming_cmd() { 
    if (http.readyState == 4) { 
       if (http.status == 200) { 
          if (http.responseText.indexOf('invalid') == -1) {
			var valores= http.responseText;
			enProceso = false;
			document.getElementById('txt_saldo').value=valores;
			if((tipo==1)|(tipo==4))
				{
				//$('#flash').flash({swf:file,height:300, width:450, wmode: 'transparent', base:baseurl});		
				if(tipo==1)
					{
					$(document).ready(function(){
					$("a#caja_loading").trigger("click");
					$('#loading').flash({swf:file,height:420, width:700, wmode: 'transparent', base:baseurl});
					});
					}
				else
					{
					$(document).ready(function(){
					$("a#caja_loading").trigger("click");
					});	
					}				
				}
			else
				{
				cont=document.getElementById('cont').innerHTML;
				flowplayer("div.player","app/includes/flowplayer/flowplayer-3.2.7.swf");
				flowplayer("div.player",{src:"app/includes/flowplayer/flowplayer-3.2.7.swf", wmode:"opaque"},{clip:{autoPlay: true,autoBuffering: true},playlist: [{baseUrl: $("base").attr("href"), url: 'app/includes/view_video.php'}],onFinish: function() {clear_video();}});	
				}
          }
       }
    }
}

function validateFormAtLeastOneField(form, msg) {
	bAtLeastOneFilled=false;
	$(':input', form).each(function() {		  		
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		if (type == 'text' || type == 'password' || tag == 'textarea')			 
			bAtLeastOneFilled=(this.value!="");			 	
		else if (type == 'checkbox' || type == 'radio')
			bAtLeastOneFilled=(this.checked == true);
		else if (tag == 'select')
			bAtLeastOneFilled=(this.selectedIndex > 0);
		if(bAtLeastOneFilled){
  			return false;//Sale del each
  		}
		
	});			
	if(!bAtLeastOneFilled){
		if(form.name=="advancedsearch2"){
			$('.searchright').html('<div class=\"notfound\">'+msg+'</div>');	
		}else{
			alert(msg);
		}
	}
	return bAtLeastOneFilled;
};

function listaListaExclusivaCon(frm, lst, lstExcluCon){			
	if(lst.options[0].selected){				
		$("#"+frm+" select[name="+lstExcluCon+"]").removeAttr("disabled");
	}else{				
		$("#"+frm+" select[name="+lstExcluCon+"]").attr("disabled", "true");
	}			
}



//Script comun a todas las paginas
$(document).ready(function() {
	
	//Login panel
	$(".signin").click(function(e) {          
		e.preventDefault();
		$("div#signin_menu").toggle();								
    });
  				
	$("div#signin_menu").mouseup(function() {
		return false
	});
	
	$(document).mouseup(function(e) {
		if($(e.target).parent("a.signin").length==0) {						
			$("div#signin_menu").hide();
		}
	});
	
	
	//Search panel				
	$("a#buscar").click(function(){					
		$("#searchpanel").toggle();					
	});
	
	$(".close").click(function(){			    
		$("#searchpanel").hide();
	});
  
  
   $(function() {
		$('#forgot_username_link').tipsy({gravity: $.fn.tipsy.autoNE});   
	});
	
	
	$("#signin_submit").click(function(e) {          
		e.preventDefault();					
	
		$('#labelerr').hide();  
		var usuario = $("input#username").val();
		if (usuario == "") {
			$("#labelerr").html(msj6);
			$("#labelerr").show();						  
			$("input#username").focus();  
			return false;  
		}
		//formato mail
		var b=/^[^@\s]+@[^@\.\s]+(\.[^@\.\s]+)+$/;
		if(b.test(usuario)==false){
			$("#labelerr").html(msj1);
			$("#labelerr").show();						  
			$("input#username").focus();  
			return false;
		}											
		var clave = $("input#password").val(); 
		if (clave == "") {							  
			$("#labelerr").html(msj6);
			$("#labelerr").show();
			$("input#password").focus();   
			return false;  
		}
		
		var dataString = "accion=login&usuario="+ usuario + "&clave=" + clave;
		
		$.ajax({
			type: "POST",
			url: "includes/consultas_ajax.php",
			data: dataString,
			success: function(datos) {
				var dataarray=datos.split("#");								
				if(dataarray[0]=="0"){
					$("#labelerr").html(dataarray[1]);
					$("#labelerr").show();									
				}else{					
					if(bReloadAfterLogin){
						window.location.reload();
					}else{						
						$("div#signin_menu").hide(); //ocultamos formulario login									
						$(".signin").hide();  //ocultamos enlace para conectar
						$("div#signed_user").html(dataarray[1]);									
						$(".signout").attr("title", dataarray[1]);									
						$(".signout").show();
					}															
				}
			}
		});
		return false;
	
	});

	$("input#password").keypress(function(e) {
		if(e.which == 13) {
		   $("#signin_submit").click();
		}
	});

	//Panel mi portal
	$(".signout").click(function(e) {          
		e.preventDefault();
		$("div#signout_menu").toggle();								
	});
			
	$("div#signout_menu").mouseup(function() {
		return false
	});

	$(document).mouseup(function(e) {
		if($(e.target).parent("a.signout").length==0) {						
			$("div#signout_menu").hide();
		}
	});
		 
  $("a.wordlink").click( function(e){
  	e.preventDefault();
		$(this).parents("form").children(":first-child").val($(this).html());
   	$(this).parents("form").submit();			    			    
  });
  
  $("a.selectlink").click( function(e){
  	e.preventDefault();
		$(this).parents("form").children(":first-child").val($(this).attr('codigo'));
   	$(this).parents("form").submit();			    			    
  });
  
  
  //Estilos por codigo para que valide el CSS
  $(".nombres_small2").css("word-wrap", "break-word");
  $(".slideRightContent ").css("word-wrap", "break-word");
  $(".detalles").css("word-wrap", "break-word");
  $(".detalles2").css("word-wrap", "break-word");
  $(".detalles_b").css("word-wrap", "break-word");
  $(".detalles2_b").css("word-wrap", "break-word");
  $(".detalles_c").css("word-wrap", "break-word");
  $(".detalles2_c").css("word-wrap", "break-word");
  $(".recurso_c3").css("word-wrap", "break-word");
  
  							
	
});
function refreshimg()
{
var randomnumber=Math.floor(Math.random()*6);
randomnumber=randomnumber+1;
document.images["code"].src="images/"+randomnumber+".gif";
var img=document.images["code"].src ;
img=img.split('/');
var c=img.length;
var x=img[c-1];
if (x=='1.gif'){document.getElementById('txt_code2').value="YJ3h2";}
if (x=='2.gif'){document.getElementById('txt_code2').value="mLg87";}
if (x=='3.gif'){document.getElementById('txt_code2').value="Ka4df";}
if (x=='4.gif'){document.getElementById('txt_code2').value="bxX22";}
if (x=='5.gif'){document.getElementById('txt_code2').value="CMK55";}
if (x=='6.gif'){document.getElementById('txt_code2').value="NMH34";}
}
function init_code()
{
var img=document.images["code"].src ;
img=img.split('/');
var c=img.length;
var x=img[c-1];
if (x=='1.gif'){document.getElementById('txt_code2').value="YJ3h2";}
if (x=='2.gif'){document.getElementById('txt_code2').value="mLg87";}
if (x=='3.gif'){document.getElementById('txt_code2').value="Ka4df";}
if (x=='4.gif'){document.getElementById('txt_code2').value="bxX22";}
if (x=='5.gif'){document.getElementById('txt_code2').value="CMK55";}
if (x=='6.gif'){document.getElementById('txt_code2').value="NMH34";}
}
