var class2;
no_seleccionado="no_sel azul";
seleccionado = "";

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; // variable para la llamada ajax que se encarga de aceptar y descartar las notificaciones
var http_2; // variable que se usa para realizar las consultas para hacer el cambio de las contrasenhas dentro del pefil_editar.php
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 pagina'); }
}    



function notificar(notificado_noti,new_noti,fecha_noti,notificador_noti,accion_noti,tipo_noti)        
{    
    //document.getElementById("preguntas_pendientes").innerHTML="<img src='http://videochat.ozu.es/administracion/img/ajax-loader.gif' border='0'> ";        
    llamadaAjax('1','/consultas_ajax/notificaciones_acciones.php?profile='+notificado_noti+'&id_notificacion='+new_noti+'&fecha='+fecha_noti+'&notificador='+notificador_noti+'&accion='+accion_noti+'&tipo='+tipo_noti,'actividad=1','devuelve_notificar');
}



function devuelve_notificar()
{
    if (http_1.readyState == 4 && (http_1.status==200 || window.location.href.indexOf("http")==-1)) 
    {
        var txt="";
        txt = http_1.responseText;
        txt = txt.split("||");
        var res_id_notificacion     = txt[0];
        var mensaje                     = txt[1];

      if ((res_id_notificacion != "undefined") && (res_id_notificacion != undefined) && (mensaje != "undefined") && (mensaje != undefined)) 
      {    
        document.getElementById("botones_"+res_id_notificacion).innerHTML= mensaje;
        }

    }
}

/////////////////////////////////////
// funciones para el control de la visibilidad de las pesta?as en completar registro

function registro_completa_marco0()
{
	document.getElementById('marco_1').className='no_sel azul';
	document.getElementById('marco_0').className= '';
	document.getElementById('completa_perfil').style.display='none';
	document.getElementById('amigos_facebook').style.display='block';
}

function registro_completa_marco1()
{
/*document.getElementById('completar_registro_1').style.display = 'inline';
document.getElementById('completar_registro_2').style.display = 'none';
document.getElementById('completar_registro_3').style.display = 'none';
document.getElementById('completar_registro_3').className='no_sel azul';
document.getElementById('marco_1').className = seleccionado;
document.getElementById('marco_2').className = no_seleccionado;
document.getElementById('marco_3').className = no_seleccionado;*/
document.getElementById('marco_0').className='no_sel azul';
document.getElementById('marco_1').className= '';
document.getElementById('completa_perfil').style.display='block';	
document.getElementById('amigos_facebook').style.display='none';
}


function registro_completa_marco2()
{
document.getElementById('completar_registro_1').style.display = 'none';
document.getElementById('completar_registro_2').style.display = 'inline';
document.getElementById('completar_registro_3').style.display = 'none';
document.getElementById('marco_1').className = no_seleccionado;
document.getElementById('marco_2').className = seleccionado;
document.getElementById('marco_3').className = no_seleccionado;
}



function registro_completa_marco3()
{
document.getElementById('completar_registro_1').style.display = 'none';
document.getElementById('completar_registro_2').style.display = 'none';
document.getElementById('completar_registro_3').style.display = 'inline';
document.getElementById('marco_1').className = no_seleccionado;
document.getElementById('marco_2').className = no_seleccionado;
document.getElementById('marco_3').className = seleccionado;
}

// funciones par la visibilidad de los menus en perfil


function perfil_menu_1()
{
document.getElementById('completar_registro_1').style.display = 'none';

}
///////////////////////////////////////
//funcion de alvaro para hacer amigos//
///////////////////////////////////////

/*
function get_actividades(id_usuario, do_pestania, paginacion=1)
{
        llamadaAjax('1','/consultas_ajax/actividades_perfil.php?user='+id_usuario+'&do='+do_pestania+'&_pagi_pg='+paginacion,'','actividades');
}
*/
function hacer_amigos(id_usuario, id)
{        
        llamadaAjax('1','/consultas_ajax/hacer_amigos.php?i='+id+'&a='+id_usuario,'num=1','devuelve_amigos_perfil');
}
function hacer_amigos_perfil(id_usuario, id)
{        
        llamadaAjax('1','/consultas_ajax/hacer_amigos.php?i='+id+'&a='+id_usuario+'&f=true','num=1','devuelve_amigos_perfil');
}

function devuelve_amigos()
{
    if (http_1.readyState == 4 && (http_1.status==200 || window.location.href.indexOf("http")==-1)) 
    {
        var txt="";
        txt = http_1.responseText;
        txt = txt.split("||");
        var res_id_notificacion     = txt[0];
        var mensaje                     = txt[1];

      if ((res_id_notificacion != "undefined") && (res_id_notificacion != undefined) && (mensaje != "undefined") && (mensaje != undefined)) 
      {    
		document.getElementById("resultado_"+res_id_notificacion).innerHTML= mensaje;
        }

    }
}
function devuelve_amigos_perfil()
{
    if (http_1.readyState == 4 && (http_1.status==200 || window.location.href.indexOf("http")==-1)) 
    {
        var txt="";
        txt = http_1.responseText;
        txt = txt.split("||");
        var res_id_notificacion     = txt[0];
        var mensaje                     = txt[1];

      if ((res_id_notificacion != "undefined") && (res_id_notificacion != undefined) && (mensaje != "undefined") && (mensaje != undefined)) 
      {    
        document.getElementById("resultado_"+res_id_notificacion).innerHTML= '<p class="elim_adm"><img src="/img/ok19.png" width="14" height="14" alt="Eliminar" title="Eliminar" border="0" />'+mensaje+'</p>';
        }

    }
}
///////////////////////////////////////////
//funci?n de alvaro para enviar la clave//
///////////////////////////////////////////
function cambio_key(mail)
{
        llamadaAjax('1','/consultas_ajax/cambiar_clave.php?mail='+mail,'','devuelve_key_form');
}

function devuelve_key_form()
{
    if (http_1.readyState == 4 && (http_1.status==200 || window.location.href.indexOf("http")==-1)) 
    {
        var txt="";
        txt = http_1.responseText;
        

        var mensaje                     = txt;

        document.getElementById("cambio_key").innerHTML= mensaje;
        

    }
}

function check_nacimiento() {
        var indice_1 = document.mas_info.dia.selectedIndex;
        var indice_2 = document.mas_info.mes.selectedIndex;
        var indice_3 = document.mas_info.anio.selectedIndex;
       if ((indice_1 ==0)||(indice_2==0)||(indice_3==0))
       {
           alert("Debe seleccionar una fecha de nacimiento correcta");
            return false;
        }else{
                    return true;
                    } 
        }
        
        
function comprobar_perfil()
{
	if((document.mas_info.publi_ok.checked) && (document.mas_info.publi_ko.checked)){
		alert("Por favor, debe marcar solamente SI desea recibir notificaciones o si NO desea recibir notificaciones");
	} else if((!document.mas_info.publi_ok.checked ) && (!document.mas_info.publi_ko.checked)){
		alert("Por favor, debe marcar una de las casillas correspondientes a si desea recibir o no notificaciones");
	} else {
		document.mas_info.submit();              
	}
}     

function validar_pseudologin()
{
	regx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;

	if(document.pseudologin.queid_email.value == ""){
		alert("Por favor, introduzca su correo ");
		document.pseudologin.queid_email.focus();
		return false;
	} else if(regx.test(document.pseudologin.queid_email.value) == false){
		alert("Por favor, introduzca un correo electronico valido");
		document.pseudologin.queid_pass.focus();
		return false;
	} else if(document.pseudologin.queid_pass.value == ""){
		alert("Por favor, introduzca su contraseña");
		document.pseudologin.queid_pass.focus();
		return false;
	/*
	} else if((document.pseudologin.publi_ok.checked) && (document.pseudologin.publi_ko.checked)){
		alert("Por favor, debe marcar solamente SI desea recibir notificaciones o si NO desea recibir notificaciones");
		return false;
	} else if((!document.pseudologin.publi_ok.checked ) && (!document.pseudologin.publi_ko.checked)){
		alert("Por favor, debe marcar una de las casillas correspondientes a si desea recibir o no notificaciones");
		return false;
	*/
	} else if(!document.getElementById('publi_ko').checked){
		alert("Por favor, debe marcar la casilla correspondiente para darse de baja y dejar de recibir notificaciones");
		return false;
	} else {
		document.pseudologin.submit();    
		return true;		
	}
	
}

function validar_login_ext_facebook()
{
	regx = /^([0-9a-zA-Z]*)$/;

	if((document.form_nuevo.id_usuario.value != "" )&& (regx.test(document.form_nuevo.id_usuario.value) == false)){
		alert("Por favor, introduzca un nombre de usuario valido o déjelo en blanco.");
		return false;
	} else if((!document.form_nuevo.publi_ok.checked ) && (!document.form_nuevo.publi_ko.checked)){
		alert("Por favor, debe marcar una de las casillas correspondientes a si desea recibir o no notificaciones");
		return false; 
	} else if(!document.form_nuevo.condiciones.checked ){
		alert("Por favor, debe aceptar las condiciones legales");
		return false;
	}
	else 
	{

		//Si existe el email es xq el portal NO ha activado el LD con FB sin mail, por lo tanto, ademas de ser obligatorio, 
		//	NO deberemos de solicitar las notificaciones via FB siendo el email ya el valido
		var email = document.getElementById("email_usuario");
		if(email == null){
			notificaciones_fb("0");			
		} else if(email.value == "" ){
			alert("Por favor, el email es obligatorio");			
		} else {			
			document.form_nuevo.submit(); 
		}		
		
		return false;		
		
	}

}     

//A esta funcion entramos desde el formulario de vuelta de FB o desde la edicion del perfil.
// param se utiliza para la edicion del perfil, si param = 1, redirigimos a un php para obtener el email de FB del usuario.
// Si venimos del formulario de login de FB NO sera necesario, param = null
function notificaciones_fb(param){
	if(typeof(FB) != 'undefined'){
		try	{
			FB.Connect.showPermissionDialog("email", function(accepted) {
				if(accepted) {
					if(param == 1){										
						//redirigimos a un php para obtener el email del usuario de FB
						id = "1";
						url_ajax ='/consultas_ajax/get_email_fb.php';		 
						$.post(url_ajax, {id_usuario: ""+id}, function(data) {
							if(data.length >0) {
								$('#notificacionesFB').html(data);
								$('#msj_notif_fb').hide();
								$('#notificacionesFB').show();								
							}  						
						});        						
					} else {
					    var input="<input type='hidden' name='notif_facebook' value='1' />";
						$("#form_nuevo").append(input);
					}
				} 
				if(param != 1){	
					document.form_nuevo.submit();    
				}
			});
		} catch(er) { }
	}
	return false;
}
       

     
        
function textCounter(field,cntfield,maxlimit) {

if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
        
// funcion para comprobrar que las dos contraseñas son correctas en editar perfil        

function perfil_modificar_contrasenhas() 
{   
        if (document.cambio_contrasenha.pwd.value != document.cambio_contrasenha.rpwd.value) 
        {
            alert("las contraseñas deben ser idénticas");
            document.cambio_contrasenha.pwd.focus();            
            return false;
        }else
            {
                document.cambio_contrasenha.submit();
            }
} 


//Esta es la funcion para realizar el cambio de las contraseñas con AJAX, pero me ha surgido el problema de el ajax envía las contraseñas sin codificar y puede ser un problema.
//Especificar que hacemos con esto.
/*
function perfil_modificar_contrasenhas()
{
   
   var pass_viejo;
   var pass_nuevo;
   var pass_nuevo2;
   
   pass_viejo = document.cambio_contrasenha.old_pwd.value;
   pass_nuevo = document.cambio_contrasenha.pwd.value;
   pass_nuevo2 = document.cambio_contrasenha.rpwd.value;
   
   
   if (pass_nuevo != pass_nuevo2) 
        {
            alert("las contraseñas deben ser idénticas");
            document.cambio_contrasenha.pwd.focus();            
            return false;
        }else
            {
                 llamadaAjax('2','/consultas_ajax/perfil_cambiar_password.php?old_pwd2='+pass_viejo+'&pwd2='+pass_nuevo+'&rpwd2='+pass_nuevo2,'','devuelve_mensaje_cambio_pass');
            }     
       
}
*/
function devuelve_mensaje_cambio_pass()
{
    if (http_2.readyState == 4 && (http_2.status==200 || window.location.href.indexOf("http")==-1)) 
    {
        var txt="";
        txt = http_2.responseText;       
        var mensaje                     = txt;
        
        
        
        //document.getElementById("cambio_key").innerHTML= mensaje;
        

    }
}       
  
    



$(document).ready(function(){
    
    $("#button_sub_2").click(function () {
      $("#camp_baja").show("slow");
    });

  });
$(document).ready(function(){
    
    $("#button_sub_2").click(function () {
      $("#button_sub_2").hide("slow");
    });

  });
  
  $(document).ready(function(){
    
    $("#privacidad_0").click(function () {
      $("#info_privacidad_1").hide();
      $("#info_privacidad_2").hide();  
      $("#info_privacidad_0").show(); 
    });
    $("#privacidad_1").click(function () {
      $("#info_privacidad_2").hide();
      $("#info_privacidad_0").hide();  
      $("#info_privacidad_1").show(); 
    });
    $("#privacidad_2").click(function () {
      $("#info_privacidad_1").hide();
      $("#info_privacidad_0").hide();  
      $("#info_privacidad_2").show(); 
    });
  });
  
  $(document).ready(function(){
    $("#mas_info_vanity").click(function () {
    $("#info_vanity_0").show();
  	});
  	$("#menos_info_vanity").click(function () {
    $("#info_vanity_0").hide();
  	});
  });
  
function validar_url_vanity()
{
	regx = /^([0-9a-zA-Z _]*)$/;
	if(document.form_vanity.vanity.value == "")
	{
		alert("Ha dejado el campo con la Vanity Url en blanco.");
		return false;
	} 
		else if(regx.test(document.form_vanity.vanity.value) == false)
	{
		alert("Ha introducido caracteres no válidos.");
		return false; 
	}
	else 
	{
		document.form_vanity.submit();    
		return true;		
	} 
}
function borrar_url_vanity()
{
	confirmar=confirm("¿Está seguro de que desea borrar su Vanity URL?"); 
	if (confirmar) 
	{
   document.form_vanity.borrar.value = 1;
   document.form_vanity.submit();    
	 	 return true;		
	}
	 else
	{ 
	 return false;
	}
    
}  

$(document).ready(function(){
    
    $("#cerrar_mensajes").click(function () {
      $("#creaCuenta2").hide();
    });

  });
  
  
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Funciones para controlar la validacion del email secundario en la administración de notificaciones //
////////////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function()
{
	$("#email_notificaciones").change(function()
	{
		if($("#email_notificaciones").val()=='1' && !email_secundario_validado)
		{
			$.ajax(
			{
				url: "consultas_ajax/validar_email_alternativo.php",
				data: ({accion: 'comprobar_email_validado'}),
				type: "POST",
				success: EnviarSolicitudValidacion
			})
		}
	})
	
	$("input[name=submit_configuracion_notificaciones_mail]").click(function()
	{
		$("input[name=email_seleccionado]").attr('value',$("#email_notificaciones").val());
	})
})

function EnviarSolicitudValidacion(resp)
{
	switch(resp)
	{
		case 'false':
			$("#email_notificaciones").attr('value','0');
			vocid_facebox('solicitar_validacion_mail');
			break;
		case 'error_bdd':
			vocid_facebox('solicitud_email_error');
			break;
		case 'true':
			email_secundario_validado = 1;
			break;
	}
}

function solicitar_validacion_mail()
{
	$("#facebox input[name=boton_solicitar_validacion]").attr('disabled','disabled');
	$.ajax(
	{
		url: "consultas_ajax/validar_email_alternativo.php",
		data:({accion: 'enviar_solicitud_validacion', email : $("#email_notificaciones option[value=1]").text()}),
		type: "POST",
		success: ValidarEmailAlternativo
	})
}

function ValidarEmailAlternativo(resp)
{
	switch (resp)
	{
		case 'OK':
		vocid_facebox('solicitud_email_enviada');
			break;
		case 'error_time':
			vocid_facebox('solicitud_email_error_time');
			break;
		default:
			vocid_facebox('solicitud_email_error');
	}
}

