//v1.0

//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs,divid) 
{ 
  var foId = null;
  var str = "<object ";
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  
  if (objAttrs["id"]=="FlashHead") params["wmode"]="window";

  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
  	if (i=='id') str += i + '="mz' + embedAttrs[i] + '" ';
    else str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';
  if (divid!=null) {
    dv = document.getElementById(divid);
    dv.innerHTML = str;
  } else document.write(str);
}

function AC_Generateobj2(objAttrs, params, embedAttrs,divid) 
{ 
  var foId = null;
  var str = "<object ";
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';

  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
  	if (i=='id') str += i + '="mz' + embedAttrs[i] + '" ';
    else str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';
  if (divid!=null) {
    dv = document.getElementById(divid);
    dv.innerHTML = str;
  } else document.write(str);
}

function AC_GenerateobjInWindow(objAttrs, params, embedAttrs, win) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';
  win.document.write(str);
}


function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs,null);
}

function AC_FL_RunContent2(){
  var ret = 
    AC_GetArgs2
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj2(ret.objAttrs, ret.params, ret.embedAttrs,arguments[0]);
}

function AC_FL_RunContentInWindow(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  ancho = ret.objAttrs["width"];
  alto = ret.objAttrs["height"];
  var a="width="+ancho+","+"height="+alto;
  flashWindow  = window.open("","flashWindow",a);
  AC_GenerateobjInWindow(ret.objAttrs, ret.params, ret.embedAttrs, flashWindow);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


function AC_GetArgs2(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=1; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}//********************************************
//
//	Copyright Mobifriends S.L. 2007
//	
//	programador: Javier Velasco Gonzalez	
//
//********************************************


// Clear user and password fields, password type is changed to password.
// This function supports Mozilla Firefox and Explorer 6 and 7.
function prepare_login_form() {
	uc = document.getElementById("user");
	uc.value = "";
	pc = document.getElementById("password");
	pc.value = "";
	var input2= pc.cloneNode(false);
	input2.type='password';
	pc.parentNode.replaceChild(input2,pc);
}

function changeCountry(countryName){
	document.getElementById('countryName').value = countryName;
}

function cambiaQueEste() {
	qediv = document.getElementById("queeste_div");
	provdiv = document.getElementById("provincia_div");
	qediv.style.visibility = 'hidden';
	qediv.style.height = '0px';
	provdiv.style.visibility = 'visible';
	provdiv.style.height = '100%';
}

function volverQueEste() {
	
	document.getElementById('renderRegions').value = 0;
	provincia = document.getElementById("provincia");
	provincia.selectedIndex = 0;
	busquedaPresentacion();
	document.getElementById('renderRegions').value = 1;
	
	qediv = document.getElementById("queeste_div");
	//qe = document.getElementById("queeste");
	provdiv = document.getElementById("provincia_div");
	qediv.style.visibility = 'visible';
	qediv.style.height = '100%';
	provdiv.style.visibility = 'hidden';
	provdiv.style.height = '0px';
	//qe.value=0;
}

function registrar() {
	Show("darmedealtaform",true);
	Show("flashprincipal",false);
	Show("darmedealta",false);
	ajax_call("darmedealtaform","php/index_registro.php",null);
	//setFlashVar("flashdarmedealta","endupdate","false");
	//setFlashVar("flashdarmedealta","cmd","register");
	//setFlashVar("flashdarmedealta","beginupdate","true");
}

function cancelRegister() {
	Show("darmedealtaform",false);
	Show("flashprincipal",true);
	Show("darmedealtaform",true);
}
	

function continuarSubirFoto() {
	Show("pagina1",false);
	Show("pagina2",true);
}

function busquedaPresentacion() {
	try {
	setFlashVar("flashdarmedealta","endupdate","false");
	setFlashVar("flashdarmedealta","cmd","search");
	setFlashVar("flashdarmedealta","beginupdate","true");
	} catch (ex) {
		alert(ex);
	}
	ajax_eval_form('buscaenmf_form','/php/index_form.php?cmd=buscar',null);
}

function busquedaAnonima() {
	setFlashVar("flashdarmedealta","endupdate","false");
	setFlashVar("flashdarmedealta","cmd","search");
	setFlashVar("flashdarmedealta","beginupdate","true");
	ajax_eval_form('buscaenmf_form','php/index_form.php?cmd=buscar',null);
}
idi_campo="El campo ";
idi_campo_no_vacio=" no debe estar vacio.";
idi_numero=" debe ser un número.";
idi_mail=" no es e-mail correcto.";
idi_susctibirse="Debe suscribirse como mínimo a un boletín";
idi_sms="El mensaje debe contener ";
idi_sms_maximo=" caracteres como máximo";
idi_destinatario="Debe seleccionar como mínimo un destinatario";
idi_borrar="Está seguro que desea borrar el elemento seleccionado?";
idi_alias_ko="El alias debe de tener una longitud igual o superior a 4 caracteres";
idi_alias_formato="El alias no debe contener espacios ni caracteres extraños";
idi_pass_ko="La contraseña debe tener una longitud igual o superior a 6 caracteres";
idi_pass_igual="Confirmación de contraseña erronea";
idi_movil_ko="Ha de introducir el numero de movil";
idi_movil_numero="El movil ha de ser un dato numerico";
idi_mail_ko="El e-mail introducido no es correcto";
idi_cp_ko="Ha de introducir un codigo postal";
idi_cp_numero="El codigo postal ha de ser un dato numerico";
idi_certifico="Debe certificar que es mayor de edad y que ha le�do las Condiciones Generales";
idi_fecha="Formato de fecha incorrecto (DD-MM-AAAA)";
idi_borrar_foto="Está seguro que desea borrar la imagen seleccionada?";
idi_principal_foto="Está seguro que desea poner como principal la imagen?";
idi_max_tam="ha de tener una longitud menor ha ";
idi_max_caracteres=" caracteres";
idi_borrar_perfil="Está seguro que desea borrar el perfil seleccionado?";
idi_borrar_perfil_no="No puede eliminar el perfil, debe haver como mínimo un perfil";var activado="";
var activado_sub="";
	
function activa(tipo)
{
	if (activado!="") document.getElementById(activado).style.display="none";
	if (activado!=tipo)
	{
		document.getElementById(tipo).style.display="";
		activado=tipo;
	}
	else activado="";
}

function activa_sub(tipo,enlace)
{
	if (document.getElementById(tipo).style.display=='none') document.getElementById(tipo).style.display="";
		else document.getElementById(tipo).style.display="none";
	if (document.getElementById(enlace).className=='expandirbw') document.getElementById(enlace).className="comprimirbw";
		else document.getElementById(enlace).className="expandirbw";
}

function comprimir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="none";
		if (valor2==enlace) v_doc[i].className="expandirbw";
	}
}

function expandir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="";
		if (valor2==enlace) v_doc[i].className="comprimirbw";
	}
}

function ocultar(tipo)
{
	document.getElementById(tipo).style.display="none";
	activado="";
}

//Comprueba el formato del correo
function verifica_mail(t_mail)
{
	if ((t_mail.lastIndexOf(" ")!=-1) || (t_mail.lastIndexOf("@")==-1) || (t_mail.lastIndexOf(".")<=(t_mail.lastIndexOf("@")+1)) || (t_mail.lastIndexOf(".")==(t_mail.length-1))) return false;
		else return true;
}

function verifica_numeros(valor)
{
	for (x=0;x<valor.length;x++)
	{
		if (isNaN(valor.substring(x,x+1))) return false;
	}
	return true;
}


function verifica_alias(t_alias)
{
	var t_ok = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
	var valido = true;
	
	tam_ok = t_ok.length;
	
	for (i=0; i<t_alias.length; i++)
	{
		ch=t_alias.charAt(i);
		for (j=0; j<tam_ok; j++)
		{
			if (ch==t_ok.charAt(j))
			{
				valido = true;
				break;
			}
			else valido = false;
		}
		if (valido==false) return false;
	}
	return true;
}

//Comprueba si ha seleccionado algun checkbox
function verifica_check_alta(formulario)
{
	var t=0;
	for (var i=0;i < formulario.elements.length;i++)
	{
		var elemento=formulario.elements[i];
		if ((elemento.type=='checkbox') && (elemento.name!='certifico'))
		{
			if (elemento.checked == true) t=1;
		}
	}
	if(t==0) return false;
		else return true;
}


function comprueba_fecha(cadena)
{
	formato_fecha=cadena.split("-");
	if (formato_fecha.length!=3) return false;
	if ((formato_fecha[0]=='') || (formato_fecha[1]=='') || (formato_fecha[2]=='')) return false;
	
	var Fecha= new String(cadena)	// Crea un string
	var RealFecha= new Date()	// Para sacar la fecha de hoy
	// Cadena Ano
	var Ano= new String(Fecha.substring(Fecha.lastIndexOf("-")+1,Fecha.length))
	// Cadena Mes
	var Mes= new String(Fecha.substring(Fecha.indexOf("-")+1,Fecha.lastIndexOf("-")))
	// Cadena Dia
	var Dia= new String(Fecha.substring(0,Fecha.indexOf("-")))

	// Valido el ano
	if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900) return false;
	
	// Valido el Mes
	if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12) return false;
	
	// Valido el Dia
	if (isNaN(Dia) || parseInt(Dia)<1 || parseInt(Dia)>31) return false;
	
	if (Mes==4 || Mes==6 || Mes==9 || Mes==11 || Mes==2)
	{
		if (Mes==2 && Dia > 28 || Dia>30) return false;
	}
	return true;
}



//Comprueba los campos obligatorios y el tipo de dato
function comprobar_campos(formulario)
{
	//Comprovamos los requeridos
	for (var i=0;i<formulario.elements.length;i++)
	{
		var e = formulario.elements[i],bvar;
		if (e.tipo=="requerido")
		{
			if (e.tam!="") //Comprueba si tiene un tamano minimo
			{
				if (e.value.length<e.tam)
				{
					if (e.tam==4) alert(idi_alias_ko);
						else  alert(idi_pass_ko);
					if (e.dato!='textarea') e.focus();
					return false;
				}
			}
			if (e.tammax!="") //Comprueba si tiene un tamano maximo
			{
				if (e.value.length>e.tammax)
				{
					alert(idi_campo + e.label + idi_max_tam + e.tammax + idi_max_caracteres);
					if (e.dato!='textarea') e.focus();
					return false;
				}
			}
			if (e.value=="")
			{
				alert(idi_campo + e.label + idi_campo_no_vacio);
				if (e.dato!='textarea') e.focus();
				return false;
			}
		}
		if (e.tipo=="repass")
		{
			if (e.value!=formulario.password.value)
			{
				alert(idi_pass_igual);
				if (e.dato!='textarea')
				{
					e.value="";
					e.focus();
				}
				return false;
			}
		}
	}
	
	//Comprovar tipo de dato
	for (var i=1;i<formulario.elements.length;i++)
	{
		var e = formulario.elements[i],bvar;
		var valor;
		if (e.value!="")
		{
			switch (e.dato)
			{
				case "numerico":
					//valor = parseFloat(e.value);
					if (isNaN(e.value))
					{
						alert(idi_campo + e.label + idi_numero);
						e.focus();
						return false;
					}
				break;
				case "mail":
					if (!verifica_mail(e.value))
					{
						alert(idi_campo + e.label + idi_mail);
						e.focus();
						return false;
					}
				break;
				case "certifico":
					if (e.checked==false)
					{
						alert(idi_certifico);
						return false;
					}
				break;
				case "fecha":
					if (comprueba_fecha(e.value)==false)
					{
						alert(idi_fecha);
						return false;
					}
				break;
			}
		}
	}
	return true;
}

//Envia alta de usuario_1
function envio_alta(formulario)
{
	if (comprobar_campos(formulario)) formulario.submit();
}

function recuperar_pass() 
{
	password=window.open('pop_password.php','password','left=50,top=50,width=300,height=100,scrollbars=auto,status=no,menubar=no,resizable=no');
}

function elimina_foto(foto) 
{
	if (confirm(idi_borrar_foto)) 
	{
		window.location='user_perfil_fotos.php?cmd=ac_user_fotos_del&orden='+foto;
	}
}

function elimina_foto_perfil(foto) 
{
	if (confirm(idi_borrar_foto)) 
	{
		window.location='user_perfil_fotos.php?cmd=ac_user_fotos_del_perfil&orden='+foto;
	}
}

function principal_foto(foto) 
{
	if (confirm(idi_principal_foto)) 
	{
		window.location='user_perfil_fotos.php?cmd=ac_user_fotos_prin&orden='+foto;
	}
}

function ini_formu_multiple(formulario)	
{
	for (var i=0;i<formulario.elements.length;i++)
	{
		var e = formulario.elements[i];
		if (e.multi=="si")
		{
			window[e.tabla] = new Array();
			var dato = e.options;
			for (var x=0, total=dato.length; x<total; x++) window[e.tabla][x] = dato[x].selected;
		}
	}
}

function cambia_formu_multiple(tabla,multiple)
{
	var dato = multiple.options;
	for (var i=0, total=dato.length; i<total; i++)
	{
		if (dato[i].selected)
		{
			tabla[i]=!tabla[i];
			ultimo=i;
		}
	}
	
	for (var i=0, total=dato.length; i<total; i++) dato[i].selected = tabla[i];
	
	dato[ultimo].selected = true;
	dato[ultimo].selected = tabla[ultimo];
}

function envio_perfil(formulario)	
{
	if (formulario.nombre_perfil.value=='')
	{
		alert('Debe introducir un nombre de perfil');
		formulario.nombre_perfil.focus();
	}
	else formulario.submit();
}

function perfil_defecto (formulario)	
{
	formulario.cmd.value='ac_busqueda_perfil_defecto'; 
	formulario.submit();
}

function perfil_editar (formulario)	
{
	formulario.cmd.value='ac_busqueda_perfil_editar'; 
	formulario.submit();
}

function perfil_elimina(formulario,num)	
{
	
	if (num>1)
	{
		if (confirm(idi_borrar_perfil))
		{
			formulario.cmd.value='ac_busqueda_perfil_del';
			formulario.submit();
		}
	}
	else alert (idi_borrar_perfil_no);
}

function carpeta_elimina(formulario)	
{
	formulario.cmd.value='ELI';
	formulario.submit();
}

function add_lista(user,tipo)	
{
	window.location='user_listado.php?user='+user+'&tipo='+tipo;
}

function func_mover(formulario,user)	
{
	document.getElementById('div_mover').style.display="";
	formulario.user.value=user;
}

function func_mover_cita(formulario,user,fecha)	
{
	document.getElementById('div_mover').style.display="";
	formulario.user.value=user;
	formulario.fecha.value=fecha;
}

function func_mover_usuario(formulario,tipo,carpeta)	
{
	document.getElementById('div_mover').style.display="none";
	formulario.tipo.value=tipo;
	formulario.carpeta.value=carpeta;
	formulario.submit();
}

function ajax_Callback()
{
	// Comprobamos si la peticion se ha completado (estado 4)
	if( ajax.readyState == 4 )
	{
		// Comprobamos si la respuesta ha sido correcta (resultado HTTP 200)
		if( ajax.status == 200 )
		{
			// Escribimos el resultado en la pagina HTML mediante DHTML
			document.getElementById("divcombo").innerHTML = ajax.responseText;
		}
	}	
}

function ajax_listado(formulario,id,datos)
{
	// Creamos el control XMLHttpRequest segun el navegador en el que estemos 
	if (window.XMLHttpRequest) ajax=new XMLHttpRequest(); // No Internet Explorer
		else ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer

	// Almacenamos en el control al funcion que se invocara cuando la peticion
	// cambie de estado
	
	ajax.onreadystatechange = ajax_Callback;
	// Enviamos la peticion
	ajax.open( "GET", "inc_combos.php?formulario=" + formulario + '&combo=' + id + datos, false );
	ajax.send( "" );
}

function mostrar_boton(form)
{
	if ((form.marca.value=='0') || (form.movil.value=='0')) document.getElementById('desc_boton').style.display="none";
		else document.getElementById('desc_boton').style.display="";
}

function descargar_movil(form) 
{
	descarga=window.open('descargas_movil.php?descarga='+form.descarga.value+'&movil='+form.movil.value,'descarga','left=50,top=50,width=200,height=150,scrollbars=auto,status=no,menubar=no,resizable=no');
}

function fun_busqueda(form,busqueda)
{
	busqueda.id_perfil_sele.value=form.id_perfil_sele.value;
	busqueda.submit();
}

function fun_comunica_add(tipo)
{
	comunica_add=window.open('user_comunica_envio_add.php?tipo='+tipo,'comunica_add','left=50,top=50,width=400,height=300,scrollbars=auto,status=no,menubar=no,resizable=no');
}

function fun_add_user(user)
{
	user_add=window.open('user_add.php?user='+user,'user_add','left=50,top=50,width=280,height=370,scrollbars=auto,status=no,menubar=no,resizable=no');
}

function fun_borrador(formulario)
{
	formulario.tipo.value='0';
	formulario.submit();
}

function fun_responder(formulario)
{
	formulario.cmd.value='ac_comu_re';
	formulario.submit();
}

function fun_eliminar(formulario)
{
	formulario.cmd.value='ac_comu_del';
	formulario.submit();
}

function fun_mover(formulario,formulario_sele)
{
	formulario.mover.value=formulario_sele.mover.value;
	formulario.cmd.value='ac_comu_mover';
	formulario.submit();
}

function fun_selecciona(seleciona,formulario,formulario_sele)
{
	for (var i=0;i<formulario.elements.length;i++)
	{
		var elemento=formulario.elements[i];
		if ((elemento.type=='checkbox') && (elemento.name!='seleccionar'))
		{
			elemento.checked=seleciona.checked;
		}
	}
	formulario_sele.seleccionar.checked=seleciona.checked;
}

function fun_selecciona_comprueba(formulario,formulario_sele)
{
	if (formulario.seleccionar.checked==true) formulario.seleccionar.checked=false;
	if (formulario_sele.seleccionar.checked==true) formulario_sele.seleccionar.checked=false;
}

function fun_crear_carpeta()	
{
	document.getElementById('div_carpeta').style.display="";
}

function fun_view_apodo()	
{
	document.getElementById('in_apodo2').style.display="none";
	document.getElementById('in_apodo').style.display="";
	document.getElementById('in_apodo').focus();
}

function fun_view_pass()	
{
	document.getElementById('in_pass2').style.display="none";
	document.getElementById('in_pass').style.display="";
	document.getElementById('in_pass').focus();
}

function verifica_edad(dia,mes,anyo)
	{	
		var fecha = new Date();
		edad=fecha.getFullYear() - anyo - 1;
    if (fecha.getMonth() + 1 - mes > 0) edad=edad + 1
		if (fecha.getMonth() + 1 - mes == 0)
		{
			 if (fecha.getDate() - dia >= 0) edad=edad + 1 
		}
		if (edad<18) return false;
			else return true;
	}

function validar_alta(formulario,validacion,myConn,tipo) 
{
	v_entra=false;
	verifica_numeros(formulario.movil.value);
	if (formulario.alias.value.length<4)
	{
		alert(idi_alias_ko);
		formulario.alias.focus();
		v_entra=true;
	}
	else if (!verifica_alias(formulario.alias.value))
	{
		alert(idi_alias_formato);
		formulario.alias.focus();
		v_entra=true;
	}
	else if (formulario.password.value.length<6)
	{
		alert(idi_pass_ko);
		formulario.password.focus();
		v_entra=true;
	}
	else if (formulario.password.value!=formulario.repassword.value)
	{
		alert(idi_pass_igual);
		formulario.repassword.value='';
		formulario.repassword.focus();
		v_entra=true;
	}
	else if (formulario.movil.value.length<9)
	{
		alert(idi_movil_ko);
		formulario.movil.focus();
		v_entra=true;
	}
	else if (!verifica_numeros(formulario.movil.value))
	{
		alert(idi_movil_numero);
		formulario.movil.focus();
		v_entra=true;
	}
	else if (!verifica_mail(formulario.mail.value))
	{
		alert(idi_mail_ko);
		formulario.mail.focus();
		v_entra=true;
	}
	else if( verifica_check_alta(formulario)==0 )
	{
		alert('Ha de seleccionar un Para');
		v_entra=true;
	}
	else if (!verifica_edad(formulario.dia.value,formulario.mes.value,formulario.any.value))
	{
		alert('Ha de ser mayor de 18 años');
		v_entra=true;
	}
	else if (formulario.cp.value=='')
	{
		alert(idi_cp_ko);
		formulario.cp.focus();
		v_entra=true;
	}
	else if (isNaN(formulario.cp.value))
	{
		alert(idi_cp_numero);
		formulario.cp.focus();
		v_entra=true;
	}
	else if (formulario.certifico.checked==false)
	{
		alert(idi_certifico);
		v_entra=true;
	}
	
	if ((v_entra==false) && (tipo==1))
	{
		/*document.getElementById('div_valida').style.display="";
		document.getElementById('div_valida').innerHTML = "<center><img src='img/cargando.gif' /></center>";
		myConn.connect("inc_web_validar.php", "GET", "alias="+formulario.alias.value+"&mail="+formulario.mail.value, validacion);*/
		comprueba=window.open('inc_web_validar.php?alias='+formulario.alias.value+'&mail='+formulario.mail.value,'comprueba','left='+screen.width/2+',top='+screen.left/2+',width=280,height=130,scrollbars=auto,status=no,menubar=no,resizable=no');
	}
	else if (v_entra==false) formulario.submit();
}

function fun_cerrar_alias() 
{
	document.getElementById('div_valida').style.display="none";
}

function fun_actualiza_cabecera(myConn,v_cabecera) 
{
	myConn.connect("inc_web_user_cabecera.php", "GET", "", v_cabecera);
	setTimeout("fun_actualiza_cabecera(myConn,v_cabecera)", 10000);
}

function fun_actualiza_online(myConn,v_online,v_ultimos) 
{
	myConn.connect("inc_web_user_online.php", "GET", "", v_online);
	setTimeout("fun_actualiza_ultimos(myConn,v_online,v_ultimos)", 100);
}

function fun_actualiza_ultimos(myConn,v_online,v_ultimos) 
{
	myConn.connect("inc_web_user_ultimos.php", "GET", "", v_ultimos);
	setTimeout("fun_actualiza_online(myConn,v_online,v_ultimos)", 10000);
}

function fun_actualiza_listado(myConn,v_listado,pagina,variables) 
{
	myConn.connect(pagina, "GET", variables, v_listado);
}

function fun_filtra_listado(myConn,v_listado,pagina,filtro,formulario) 
{
	filtro.filtrado.value=1;
	if (filtro.filt_user.checked==true) v_online=1;
		else v_online=0;
	if (filtro.foto.checked==true) myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value+"&filt_user="+v_online+"&pais="+filtro.pais.value+"&provincia="+filtro.provincia.value+"&cp="+filtro.cp.value+"&foto=1", v_listado);
		else myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value+"&filt_user="+v_online+"&pais="+filtro.pais.value+"&provincia="+filtro.provincia.value+"&cp="+filtro.cp.value, v_listado);
}

function fun_ordena_listado(myConn,v_listado,pagina,filtro,formulario) 
{
	if (filtro.filtrado.value=='0') myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value, v_listado);
		else fun_filtra_listado(myConn,v_listado,pagina,filtro,formulario);
}

function fun_filtra_listas(myConn,v_listado,pagina,filtro,formulario) 
{
	filtro.filtrado.value=1;
	if (filtro.filt_user.checked==true) v_online=1;
		else v_online=0;
	if (filtro.foto.checked==true) myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value+"&tipo="+formulario.tipo.value+"&carpeta="+formulario.carpeta.value+"&filt_user="+v_online+"&pais="+filtro.pais.value+"&provincia="+filtro.provincia.value+"&cp="+filtro.cp.value+"&foto=1", v_listado);
		else myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value+"&tipo="+formulario.tipo.value+"&carpeta="+formulario.carpeta.value+"&filt_user="+v_online+"&pais="+filtro.pais.value+"&provincia="+filtro.provincia.value+"&cp="+filtro.cp.value, v_listado);
}

function fun_ordena_listas(myConn,v_listado,pagina,filtro,formulario) 
{
	if (filtro.filtrado.value=='0') myConn.connect(pagina, "GET", "orden="+formulario.orden.value+"&de="+formulario.de.value+"&tipo="+formulario.tipo.value+"&carpeta="+formulario.carpeta.value, v_listado);
		else fun_filtra_listas(myConn,v_listado,pagina,filtro,formulario);
}

function fun_ordena_comunicacion(myConn,v_listado,pagina,tipo,carpeta,orden,orden_desc,busca,buscaren) 
{
	myConn.connect(pagina, "GET", "tipo="+tipo+"&carpeta="+carpeta+"&orden="+orden+"&orden_desc="+orden_desc+"&busca="+busca+"&buscaren="+buscaren, v_listado);
}

function fun_eliminar_carpeta(formulario) 
{
	if (confirm("Esta seguro que desea eliminar la carpeta y todo su contenido?"))
	{
		formulario.cmd.value="ac_comu_carp_del";
		formulario.submit();
	}
}

function fun_refrescar() 
{
	window.location=window.location;
}

function fun_posicion_alias() 
{
	/*document.getElementById('div_valida').style.left=(780/2)-100;
	document.getElementById('div_valida').style.top=(screen.height/2)-200;*/
	document.getElementById('div_valida').style.left=0;
	document.getElementById('div_valida').style.top=0;
}

function fun_activar_perfil(myConn,div_capa,seleccion,valor)
{
	myConn.connect("inc_combos.php", "GET", "formulario=2&valor="+valor+"&seleccion"+seleccion, div_capa);
}

function fun_alias_disponible(formulario,validacion,myConn) 
{
	if ((formulario.alias.value!='') && (formulario.alias.value.length>=4))
	{
		comprueba=window.open('inc_web_validar.php?alias='+formulario.alias.value,'comprueba','left='+screen.width/2+',top='+screen.left/2+',width=280,height=130,scrollbars=auto,status=no,menubar=no,resizable=no');
		/*document.getElementById('div_valida').innerHTML = "";
		document.getElementById('div_valida').style.display="";
		myConn.connect("inc_web_validar.php", "GET", "alias="+formulario.alias.value, validacion);*/
	}
}

function fun_selecciona_alias(formulario,formu) 
{
	for (i=0;i<formulario.v_alias.length;i++)
	{
		if (formulario.v_alias[i].checked) break;
	}
	formu.alias.value=formulario.v_alias[i].value;
	window.close();
}

function fun_busqueda_opciones(activado)
{
	if (document.getElementById(activado).style.display=="none") 
	{
		document.getElementById(activado).style.display="";
		if (activado=='div_opciones_perfil') document.getElementById('masopca').id="masopca1";
			else document.getElementById('masopcr').id="masopcr1";
	}
	else 
	{
		document.getElementById(activado).style.display="none";
		if (activado=='div_opciones_perfil') document.getElementById('masopca1').id="masopca";
			else document.getElementById('masopcr1').id="masopcr";
	}
}

function fun_filtro_listas(activado)
{
	if (document.getElementById(activado).style.display=="none") 
	{
		document.getElementById(activado).style.display="";
		document.getElementById('img_filtro').src="images/botones/fletxeta_up.gif";
	}
	else 
	{
		document.getElementById(activado).style.display="none";
		document.getElementById('img_filtro').src="images/botones/fletxeta_do.gif";
	}
}

function fun_elimina_lista(id)
{
	window.location="user_listas_mis_listas.php?cmd=ac_user_lista_del&id="+id+"&pagina="+window.location;
}

function fun_buscar_perfil(formulario)
{
	formulario.action='user_busqueda.php';
	formulario.cmd.value='ac_busqueda';
	formulario.submit();
}

function fun_comu_cc(activado)
{
	document.getElementById(activado).style.display="";
}

function fun_alias_disponible(formulario,validacion,myConn) 
{
	if ((formulario.alias.value!='') && (formulario.alias.value.length>=4))
	{
		comprueba=window.open('inc_web_validar.php?alias='+formulario.alias.value,'comprueba','left='+screen.width/2+',top='+screen.left/2+',width=280,height=130,scrollbars=auto,status=no,menubar=no,resizable=no');
		/*document.getElementById('div_valida').innerHTML = "";
		document.getElementById('div_valida').style.display="";
		myConn.connect("inc_web_validar.php", "GET", "alias="+formulario.alias.value, validacion);*/
	}
}

function fun_comu_validar_usuario(myajax,myConn,tipo,validacion,formulario)
{
	switch (tipo)
	{
		case 'para': 
			v_campo=formulario.para.value;
			v_user=formulario.valida_para.value;
			myajax.Value('inc_validar_comunicacion_usuario.php?para=' + v_campo+ '&usuario=' + v_user, tipo);
			myConn.connect("inc_validar_comunicacion.php", "GET", "para="+v_campo+"&usuario="+v_user, validacion);
			formulario.valida_para.value='';
		break;
		case 'cc': 
			v_campo=formulario.cc.value;
			v_user=formulario.valida_cc.value;
			myajax.Value('inc_validar_comunicacion_usuario.php?cc=' + v_campo + '&usuario=' + v_user, tipo);
			myConn.connect("inc_validar_comunicacion.php", "GET", "cc="+v_campo+"&usuario="+v_user, validacion); 
			formulario.valida_cc.value='';
		break;
	}
}

function fun_comu_validar_usuario_res(myajax,myConn,tipo,validacion,formulario,responde)
{
	switch (tipo)
	{
		case 'para': 
			v_campo=formulario.para.value;
			v_user=formulario.valida_para.value;
			myajax.Value('inc_validar_comunicacion_usuario.php?para=' + v_campo+ '&usuario=' + v_user, tipo);
			myConn.connect("inc_validar_comunicacion.php", "GET", "para="+v_campo+"&usuario="+v_user+"&responde="+responde, validacion);
			formulario.valida_para.value='';
		break;
		case 'cc': 
			v_campo=formulario.cc.value;
			v_user=formulario.valida_cc.value;
			myajax.Value('inc_validar_comunicacion_usuario.php?cc=' + v_campo + '&usuario=' + v_user, tipo);
			myConn.connect("inc_validar_comunicacion.php", "GET", "cc="+v_campo+"&usuario="+v_user+"&responde="+responde, validacion); 
			formulario.valida_cc.value='';
		break;
	}
}

function fun_comu_eliminar_usuario(myConn,tipo,validacion,formulario,posicion,responde)
{
	var v_usuarios = new Array();
	v_texto="";
	switch (tipo)
	{
		case 'para': 
			v_usuarios = formulario.para.value.split(";");
			for(i=0;i<v_usuarios.length;i++)
			{
				if (i!=posicion)
				{
					if (v_texto=='') v_texto=v_usuarios[i];
						else v_texto=v_texto+";"+v_usuarios[i];
				}
			}

			formulario.para.value=v_texto;
			v_campo=v_texto;
			myConn.connect("inc_validar_comunicacion.php", "GET", "para="+v_campo+"&responde="+responde, validacion);
			formulario.valida_para.value='';
		break;
		case 'cc': 
			v_usuarios = formulario.cc.value.split(";");
			for(i=0;i<v_usuarios.length;i++)
			{
				if (i!=posicion)
				{
					if (v_texto=='') v_texto=v_usuarios[i];
						else v_texto=v_texto+";"+v_usuarios[i];
				}
			}

			formulario.cc.value=v_texto;
			v_campo=v_texto;
			myConn.connect("inc_validar_comunicacion.php", "GET", "cc="+v_campo+"&responde="+responde, validacion); 
			formulario.valida_cc.value='';
		break;
	}
}

function fun_comu_anadir_usuario(myConn,tipo,validacion,form_favoritos,formulario,favoritos,responde)
{
	v_texto="";
	for (var i=0;i<form_favoritos.elements.length;i++)
	{
		var elemento=form_favoritos.elements[i];
		if (elemento.type=='checkbox')
		{
			if (elemento.checked == true)
			{
				if (v_texto=="") v_texto=elemento.value;
					else v_texto=v_texto+";"+elemento.value;
				elemento.checked=false;
			}
		}
	}
	switch (tipo)
	{
		case 'para': 
			if (formulario.para.value=='') v_campo=v_texto;
				else v_campo=formulario.para.value+";"+v_texto;
			myConn.connect("inc_validar_comunicacion.php", "GET", "para="+v_campo+"&responde="+responde, validacion);
			formulario.para.value=v_campo;
		break;
		case 'cc':
			if (formulario.cc.value=='') v_campo=v_texto;
				else v_campo=formulario.cc.value+";"+v_texto;
			myConn.connect("inc_validar_comunicacion.php", "GET", "cc="+v_campo+"&responde="+responde, validacion); 
		formulario.cc.value=v_campo;
		break;
	}
	
	document.getElementById(favoritos).style.display="none";
}

function fun_ocultar_favoritos(activado)
{
	document.getElementById(activado).style.display="none";
}

function fun_mostrar_favoritos(myConn,validacion,activado,formulario,tipo)
{
	document.getElementById(activado).style.display="";
	myConn.connect("inc_favoritos.php", "GET", "tipo="+tipo, validacion);
}

function fun_mostrar_anadir(myConn,validacion,activado,user)
{
	document.getElementById(activado).style.display="";
	myConn.connect("inc_pop_anadir.php", "GET", "user="+user, validacion);
}

function fun_mostrar_favoritos_res(myConn,validacion,activado,formulario,tipo,responde)
{
	document.getElementById(activado).style.display="";
	myConn.connect("inc_favoritos.php", "GET", "tipo="+tipo+"&responde="+responde, validacion);
}

function fun_valida_documentacion(formulario)
{
	if (formulario.para.value=='')
	{
		alert('Debe enviar el mensaje a algun usuario');
	}
	else if (formulario.asunto.value=='')
	{
		alert('Debe escribir un asunto');
		formulario.asunto.focus();
	}
	else if (formulario.mensaje.value=='')
	{
		alert('Debe escribir un mensaje');
		formulario.mensaje.focus();
	}
	else formulario.submit();
}

function fun_valida_mobi(formulario)
{
	if (formulario.para.value=='')
	{
		alert('Debe enviar el mensaje a algun usuario');
	}
	else formulario.submit();
}

function fun_password()
{
	pop_password=window.open('pop_pass.php','pop_password','left=50,top=50,width=280,height=218,scrollbars=no,status=no,menubar=no,resizable=no');
}

function fun_verifica_password(formulario)
{
	if (formulario.password.value=='')
	{
		alert('Debe introducir la contraseña actual');
		formulario.password.focus();
	}
	else if (formulario.new_password.value=='')
	{
		alert('Debe introducir la nueva contraseña');
		formulario.new_password.focus();
	}
	else if (formulario.new_password.value.length<6)
	{
		alert('La contraseña ha de ser de tener 6 o mas caracteres');
		formulario.new_password.focus();
	}
	else if (formulario.re_new_password.value!=formulario.new_password.value)
	{
		alert('La confirmaion de contraseña incorrecta');
		formulario.re_new_password.focus();
	}
	else formulario.submit();
}

function fun_carp_nombre(carpeta,tipo)
{
	pop_carp_nombre=window.open('pop_carpeta_nombre.php?carpeta='+carpeta+'&tipo='+tipo,'pop_carp_nombre','left=50,top=50,width=280,height=130,scrollbars=no,status=no,menubar=no,resizable=no');
}

function fun_carp_crear(carpeta,tipo)
{
	pop_carp_nombre=window.open('pop_carpeta_crear.php?carpeta='+carpeta+'&tipo='+tipo,'pop_carp_nombre','left=50,top=50,width=280,height=180,scrollbars=no,status=no,menubar=no,resizable=no');
}

function fun_foto_ver(foto,user)
{
	pop_foto=window.open('pop_foto.php?foto='+foto+'&user='+user,'pop_foto','left=50,top=50,width=630,height=660,scrollbars=no,status=no,menubar=no,resizable=no');
	pop_foto.focus();
}

function fun_mostrar_perfil(tipo)
{
	if (document.getElementById(tipo).style.display=="") document.getElementById(tipo).style.display="none";
		else document.getElementById(tipo).style.display="";
}

function fun_mostrar_codigo(myConn,v_codigo) 
{
	if (div_entra==1)
	{
		myConn.connect("inc_codigo_foto.php", "GET", "", v_codigo);
		div_entra=2;
	}
}

function fun_mostrar_codigo2() 
{
	document.getElementById('div_clave2').innerHTML=document.getElementById('div_clave').innerHTML;
}

function fun_pop_foto(num)
{
	pop_foto=window.open('pop_foto_subir.php?num='+num,'pop_foto','left=50,top=50,width=280,height=120,scrollbars=no,status=no,menubar=no,resizable=no');
}

function fun_verifica_cuenta_mail(formulario)
{
	if (formulario.nombres.value=='')
	{
		alert('Debe introducir un nombre');
		formulario.nombres.focus();
	}
	else if (formulario.mails.value=='')
	{
		alert('Debe introducir un email');
		formulario.mails.focus();
	}
	else formulario.submit();
}

function fun_verifica_cont_user(formulario)
{
	if (formulario.nombre.value=='')
	{
		alert('Debe introducir un nombre de usuario');
		formulario.nombre.focus();
	}
	else if (!verifica_mail(formulario.email.value))
	{
		alert('Debe introducir un email correcto');
		formulario.email.focus();
	}
	else if (formulario.mensaje.value=='')
	{
		alert('Debe introducir un mensaje');
		formulario.mensaje.focus();
	}
	else formulario.submit();
}

function fun_verifica_cont_trabaja_manda(formulario)
{
	if (formulario.nombre.value=='')
	{
		alert('Debe introducir un nombre');
		formulario.nombre.focus();
	}
	else if (formulario.apellidos.value=='')
	{
		alert('Debe introducir un apellido');
		formulario.apellidos.focus();
	}
	else if (!verifica_mail(formulario.email.value))
	{
		alert('Debe introducir un email correcto');
		formulario.email.focus();
	}
	else if (formulario.telefono.value=='')
	{
		alert('Debe introducir un teléfono de contacto');
		formulario.telefono.focus();
	}
	else if (formulario.direccion.value=='')
	{
		alert('Debe introducir una dirección');
		formulario.direccion.focus();
	}
	else if (formulario.cv.value=='')
	{
		alert('Debe introducir su CV');
		formulario.cv.focus();
	}
	else formulario.submit();
}

function iSubmitEnter(oEvento, oFormulario)
{ 
	var iAscii;
	if (oEvento.keyCode) iAscii = oEvento.keyCode; 
		else if (oEvento.which) iAscii = oEvento.which; 
			else return false; 
	if (iAscii == 13) submitFormById(oFormulario); 
	return true; 
} 

function fun_busca_comu(formulario)
{
	if ((formulario.buscaren.value==1) || (formulario.buscaren.value==3)) formulario.tipo.value="";
		else formulario.tipo.value="1";
	formulario.submit();
}

function fun_form_focus(tipo,input)
{
	document.getElementById(tipo).style.color="#F88507";
	input.style.background="#FBD6AE";
}

function fun_form_focus2(tipo,input)
{
	document.getElementById(tipo).style.color="#000000";
	input.style.background="#FBD6AE";
}

function fun_form_blur(tipo,input)
{
	document.getElementById(tipo).style.color="";
	input.style.background="";
}//********************************************
//
//	Copyright Mobifriends S.L. 2007
//	
//	programador: Javier Velasco Gonzalez	
//
//********************************************


//********************************************
// devuelve la version de explorer o 0.
//--------------------------------------------
function isExplorer() {
	if (navigator.appName=="Microsoft Internet Explorer") {
		var iversion = navigator.appVersion.indexOf("MSIE ");
		if (iversion>0) {
			iversion+=5;
			var eversion = navigator.appVersion.indexOf(";",iversion);
			var version = navigator.appVersion.substring(iversion,eversion);
			return parseInt(version);
		}
	} else return 0;
}

//********************************************
// devuelve la version de firefox o 0.
//--------------------------------------------
function isFirefox() {
	if (navigator.appName.indexOf("Netscape")!=-1 && parseInt(navigator.appVersion)>=5) {
		var iversion = navigator.userAgent.indexOf("Firefox/");
		if (iversion>0) {
			iversion+=8;
			var eversion = navigator.userAgent.indexOf(" ",iversion);
			if (eversion<navigator.userAgent.length) eversion = navigator.userAgent.length;
			var version = navigator.userAgent.substring(iversion,iversion + 1000);
			return parseInt(version);
		} else return 0;
	}
	else return 0;
}


function getWindowWidth() {
  var width = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    if( document.body && document.body.clientWidth) width = document.body.clientWidth;
    else width = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth) {
    //IE 6+ in 'standards compliant mode'
    width = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth) {
    //IE 4 compatible
    width = document.body.clientWidth;
  }
  return width;
}

function getWindowHeight() {
  var height = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    if( document.body && document.body.clientHeighth) height = document.body.clientHeight;
    else height = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    height = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    height = document.body.clientHeight;
  }
  return height;
}


function getDocumentHeight() {
	var height = document.height;
	//if (!height) height = document.docubody.clientHeight;
	if (!height) height = document.documentElement.scrollHeight;

	if (height<getWindowHeight()) height = getWindowHeight();

	return height;
}


function getDocumentWidth() {
	var width = document.width;
//	if (!width) width = document.body.clientWidth;
	if (!width) width = document.documentElement.scrollWidth;
	if (width<getWindowWidth()) width = getWindowWidth();
	return width;
}

function getHScrollPos() {
	var vExplorer = isExplorer();
	var pos;
	if (vExplorer) {
		pos = document.documentElement.scrollLeft;
		if (!pos) pos = document.body.scrollLeft;
	} else {
		pos=window.pageXOffset;		
	}
	return pos;	
}

function getVScrollPos() {
	var vExplorer = isExplorer();
	var pos;
	if (vExplorer) {
		pos = document.documentElement.scrollTop;
		if (!pos) pos = document.body.scrollTop;
	} else {
		pos=window.pageYOffset;		
	}
	return pos;	
}

function getVScrollAdjustments() {
	var screenHeight = getWindowHeight();
	var vScrollPos =  getVScrollPos();
	return screenHeight +"," +vScrollPos;
}


//********************************************
// envia el formulario con el id = formid.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//
// @return: 
//
//********************************************
function submitFormById(formid) {
	f = document.getElementById(formid)
	f.submit();
}

//********************************************
// devuelve el valor de un campo.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//	devuelve el valor de un campo en funcion de el id.
//
//********************************************
function getValue(id) {
	f = document.getElementById(id);
	return f.value;
}

//********************************************
// establece el valor de un campo.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//
//********************************************
function setValue(id,value) {
	f = document.getElementById(id);
	if (f==null) return;
	switch (f.tagName.toLowerCase()) {
		case "select":
			f.value = value;
		break;
		case "input":
			f.value = value;
			if (f.type=="checkbox") {
				if (value==0) f.checked = null;
				else f.checked= true;
			}
		break;
		case "div":
			otype = document.getElementById(id+"__type");
			olenght = document.getElementById(id+"__length");
			if (otype==null) return;
			switch (otype.value) {
				case "mcheckbox":
					for (i=0;i<olenght.value;i++) {
						o = document.getElementById(id+String(i));
						if (o.value==value) {
							o.checked = true;
							return;
						}
					}
				break;				
			}
		break;
	}
}


//********************************************
// limpia los checkboxes 
//--------------------------------------------
//
// @params:
//	id: id del multiple checkbox.
//
// @return: 
//
//********************************************
function clearMCheckbox(id) {
	f = document.getElementById(id);
	if (f==null) return;
	otype = document.getElementById(id+"__type");
	olenght = document.getElementById(id+"__length");
	if (otype==null || otype.value!="mcheckbox") return;
	for (i=0;i<olenght.value;i++) {
		o = document.getElementById(id+String(i));
		o.checked=null;
	}
}

//********************************************
// borra todas las referencias dentro de un objeto
// de forma recursiva.
// Se usa para prevenir el memory leak de explorer,
// tiene que ser llamada antes de un setInnerHTML
// y antes de un removeChild.
//--------------------------------------------
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
        	try{
            	n = a[i].name;
            }catch(e){
            	return;
            }
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}
//********************************************
// establece el html dentro de una etiqueta.
//--------------------------------------------
//
// @params:
//	id: id del campo.
//
// @return: 
//
//********************************************
function setInnerHTML(id,text) {
	f = document.getElementById(id);
	if (f==null) return;//alert("No encuentra" + id);
	else {
		if (isExplorer()) purge(f);
		f.innerHTML = text;
	}
}


function urldecode( str ) {
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    ret = decodeURIComponent(ret);
    return ret;
}

function striptags(str) {
	var flip = false;
	var result="";
	for (c in str) {
		if (str[c]=='<') flip=true;
		else if (str[c]=='>') flip=false;
		else if (!flip) result+=str[c];
	}
	return result;
}


function setInnerEHTML(id,text) {
	f = document.getElementById(id);
	if (f==null) return; //alert("No encuentra" + id);
	else {
		purge(f);
		f.innerHTML = urldecode(text);
	}
}


//Rellena un campo select con valores numericos.
function fillNumbersCombo(id,nini,nfin,value,rellenarconceros) {
	options = "";
	snfin = nfin.toString();
	snini = nini.toString();
	maxlen = snfin.length;
	if (snini.length>maxlen) maxlen = snini.length ;
	/*
	for (i=nini;;) {
		stri = i.toString();
		if (rellenarconceros) {
			len = stri.length;
			for (j=0;j<maxlen-len;j++) stri = "0"+stri;
		}
		if (value!=i) options += "<option value='" + i.toString()+"'>" + stri + "</option>";
		else options += "<option selected='true' value='" + i.toString()+"'>" + stri + "</option>";
		//test del loop.		
		if (nini<nfin) {
			if (i>=nfin) break;
			i++
		} else {
			if (i<=nfin) break;
			i--;
		}
	}*/
	setInnerHTML(id,options);
}

//********************************************
// devuelve el valor de un elemento del tipo INPUT.
//--------------------------------------------
//
// @params:
//	fieldid: id del elemento INPUT.
//
// @return: 
//	devuelve una cadena con el valor del INPUT
//
//********************************************
function getInputValueById(fieldid) {
	f = document.getElementById(fieldid)
	return f.value;
}

//********************************************
// cambia el elemento seleccionado en un SELECT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	comboname: nombre del campo SELECT.
//	value: attributo value del OPTION a seleccionar.
//
// @return: 
//	devuelve una cadena con el valor del INPUT
//
//********************************************
function setComboByValue(formid,comboname,value) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[comboname];
	} else {
		element = f.all[comboname];
	}
	var attrs="";
	for (i=0;i<element.length;i++) {
		var option = element[i];
		if (option.tagName=="OPTION" && 
			option.value==value) {
			element.selectedIndex=i;
		} 
	}
}

//********************************************
// cambia el elemento seleccionado en un SELECT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	comboname: nombre del campo SELECT.
//	text: texto de la opcion a seleccionar.
//
// @return: 
//
//********************************************
function setComboByText(formid,comboname,text) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[comboname];
	} else {
		element = f.all[comboname];
	}
	var attrs="";
	for (i=0;i<element.length;i++) {
		var option = element[i];
		if (option.tagName=="OPTION" && 
			option.innerText==text) {
			element.selectedIndex=i;
		} 
	}
}

//********************************************
// establece el valor de un campo INPUT.
//--------------------------------------------
//
// @params:
//	formid: attributo id del form.
//	fieldname: nombre del campo INPUT.
//	value: valor para el campo INPUT.
//
// @return: 
//
//********************************************
function setInput(formid,fieldname,value) {
	f = document.getElementById(formid)
	if(typeof XMLHttpRequest!='undefined') {
		element = f.elements[fieldname];
	} else {
		element = f.all[fieldname];
	}
	element.value = value;
}

//********************************************
// devuelve el estilo de un elemento.
//--------------------------------------------
//
// @params:
//	id: attributo id del elemento.
//
// @return: 
//
//********************************************
function getStyleById(id) {
	element = document.getElementById(id)
	return element.style;
}


//Funciones de validacion

//********************************************
// valida que sea una direccion de correo valida.
//--------------------------------------------
//
// @params:
//	email: cadena de texto que contiene el email.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateEmail(email) {
	var parts = email.split('@');
	if (parts.length!=2) return false;
	var user = parts[0];
	var server = parts[1];
	parts = server.split('.');
	if (parts.length<1) return false;
	else return true;
}

//********************************************
// valida que sea un numero.
//--------------------------------------------
//
// @params:
//	number: cadena de texto que contiene el numero.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateIsNumber(number) {
	for (i=0;i<number.length;i++) {
		var ch = number.charAt(i);
		if (ch!='0' && ch!='1' && ch!='2' && ch!='3' && ch!='4' && ch!='5' && ch!='6' && ch!='7' && ch!='8' && ch!='9')
		return false;
	}
	return true;
}

//********************************************
// valida que sea un numero de telefono valido.
//--------------------------------------------
//
// @params:
//	number: cadena de texto que contiene el numero.
//
// @return: 
//	true si es correcta o false si es incorrecta.
//
//********************************************
function validateIsPhoneNumber(number) {
	for (i=0;i<number.length;i++) {
		var ch = number.charAt(i);
		if (ch!='0' && ch!='1' && ch!='2' && ch!='3' && ch!='4' && ch!='5' && ch!='6' && ch!='7' && ch!='8' && ch!='9')
		return false;
	}
	return true;
}


var WINDOW_TYPE_MODAL 	= 1;
var WINDOW_HCENTERED 	= 2;
var WINDOW_VCENTERED 	= 4;

var __windows = new Array();
var __zIndex = 1000;

function CreateIFrame(id,x,y,width,height,color,opac) {
        var windowdiv = document.createElement('iframe');
        windowdiv.setAttribute('id',id);
        windowdiv.setAttribute('class',"windowiframe");
        windowdiv.src='javascript:false;';
        zi = __zIndex++;
        var div = document.getElementsByTagName("body")[0];
        if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
        windowdiv.style.position="absolute";
        windowdiv.style.zIndex=zi;
        windowdiv.style.top=y;
        windowdiv.style.left=x;
        if (width!=null)  windowdiv.style.width=width;
        if (height!=null) windowdiv.style.height=height;
        if (color!=null) windowdiv.style.background = color;
        div.appendChild(windowdiv);
        __windows.push(windowdiv);
}


var allSelects = new Array(); //fix Explorer 6, array con los selects.
var activeWindows = 0; // for fix window mode on flash objects in IE
//********************************************
// Crea una div dinamicamente
//--------------------------------------------
//
// @params:
//	id: atributo id de la div.
//	x: posicion x dentro de la ventana, debe ser expresada como cadena indicando la unidad %,px etc.
//	y: posicion y dentro de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	width: ancho de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	height: alto de la ventana, debe ser expresada como cadena indicando la unidad %,px etc
//	html: contenido xhtml de la div.
//	color: color de fondo si lo tuviera sino el atributo es omitido (transparente).
//	opac: opacidad de la capa indicado en %.
//
// @return: 
//
//********************************************
function CreateWindow(id,x,y,width,height,html,color,opac,sClassName) {
	
	var windowdiv = document.createElement('div');
	var vExplorer = isExplorer();
	var windowClass = "string" === typeof sClassName ? sClassName:"window";
	
	windowdiv.setAttribute('id',id);
	windowdiv.setAttribute('class',windowClass);
	__zIndex+=500;
	zi = __zIndex;
	var div = document.getElementsByTagName("body")[0];
	if (isFirefox()) {
	    if (opac!=null) {
	    	fopac = opac/100;
	    	windowdiv.style.MozOpacity=fopac;
	    }
	} 
	if (vExplorer>6) {
		if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
		windowdiv.style.position="absolute";
	} else if (vExplorer<=6 && vExplorer>3) {
		if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
		windowdiv.style.position="absolute";
	} else {
		windowdiv.style.position="fixed";
	}
	//a�adidos para cambiar la opacity de Opera y Safari
	//como no hay funcion para detectar estos navegadores y no afecta a los otros lo he puesto directamente aqui.
	if (opac!=null) {
	  	fopac = opac/100;
	   	windowdiv.style.opacity=fopac;
	}
	
	windowdiv.innerHTML = html;
	windowdiv.style.display="block";
	windowdiv.style.top=y;
	windowdiv.style.left=x;

	if (vExplorer>=8) {
		div.style.zIndex=10;
		windowdiv.style.zIndex=zi;
	} else {
		windowdiv.style.zIndex=zi;
	}
	if (width!=null)  windowdiv.style.width=width;
	if (height!=null) windowdiv.style.height=height;
	if (color!=null) windowdiv.style.background = color;
	div.appendChild(windowdiv);
}

function updateFlashHeaderWindowMode(wmode){
	var vExplorer = isExplorer();
    //alert(vExplorer + "::" + wmode);

	//if(vExplorer === 0) return;
	var flashObj = document.getElementById('FlashHead');
	if(flashObj === null) return;

	var container = document.getElementById('header_wrapper');
	
	if(container === null){
		// Create the div and append to header div
		container = document.createElement('div');
		container.id = 'header_wrapper';
		container.style.position = 'relative';
		container.style.margin = '0';
		container.style.padding = '0';
		container.style.backgroundColor = '#ffffff';
		
		var menu = document.getElementById('cabmenu');
		if(menu !== null){
			document.getElementById('cabecera').removeChild(menu);
		}
		document.getElementById('cabecera').appendChild(container);
		document.getElementById('cabecera').appendChild(menu);
	}
	
	// Remove the old flash
	var parentNode = flashObj.parentNode;
	purge(flashObj);
	parentNode.removeChild(flashObj);
	
	for(var i=0;i<flashObj.childNodes.length;i++){
		flashObj[i] = null;
	}
	
	flashObj = null;
	
	// Load wrapper with new flash
	AC_FL_RunContent2('header_wrapper','codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,19,0',
               'width','780px',
               'height','128px',
               'src','flash/head',
               'quality','high',
               'bgcolor','#ffffff',
               'name','head',
               'allowscriptaccess','sameDomain',
               'pluginspage','http://www.macromedia.com/go/getflashplayer',
               'scale','noborder',
               'wmode', wmode,
               'flashvars', '',
               'id', 'FlashHead',   
               'movie','flash/head' );
}

function CreateIEWindow(id,x,y,width,height,html,color,opac) {
	var windowdiv = document.createElement('div');
	var vExplorer = isExplorer();
	windowdiv.setAttribute('id',id + "_parent");
	//windowdiv.setAttribute('class',"window");
	
	var div = document.getElementsByTagName("body")[0];
	if (opac!=null) windowdiv.style.filter = "alpha(opacity=" + opac + ")";
	windowdiv.style.position="absolute";
	//a�adidos para cambiar la opacity de Opera y Safari
	//como no hay funcion para detectar estos navegadores y no afecta a los otros lo he puesto directamente aqui.
	if (opac!=null) {
	  	fopac = opac/100;
	   	windowdiv.style.opacity=fopac;
	}
	divzi = __zIndex++;
	zi = __zIndex++;
	html = "<iframe style='position:absolute; "+
			" src='javascript:false;'" + 
			" top:0px;" + 
			" left:0px;" + 
			" width: 1px;" + 
			" height: 1px;" +
			" z-index: " + zi + ";'" + 
			" id='" + id + "_iframe' >'</iframe>";
	zi = __zIndex++;
	html = html + "<div style='position:absolute; top:0px; left:0px; " + 
			"z-index:" + zi +";' id='" + id + "' ></div>";	
	windowdiv.innerHTML = html;
	windowdiv.style.display="block";
	windowdiv.style.zIndex=divzi;
	windowdiv.style.top=y;
	windowdiv.style.left=x;
	if (width!=null)  windowdiv.style.width=width;
	if (height!=null) windowdiv.style.height=height;
	if (color!=null) windowdiv.style.background = color;
	div.appendChild(windowdiv);
	__windows.push(windowdiv);
	iframe = document.getElementById(id+"_iframe");
	newdiv = document.getElementById(id);
	iframe.style.width = newdiv.clientWidth;
	iframe.style.height = newdiv.clientHeight;
}


var __window_selected=null;


// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xStartPos = null; // Horizontal position of the mouse on the screen
yStartPos = null; // Vertical position of the mouse on the screen

function captureMousePosition(e) {
	var vExplorer = isExplorer();
	if (!e) e = window.event;
	if (!e.pageX) {
    	xMousePos = e.clientX;
    	yMousePos = e.clientY;
    	
	} else {
    	xMousePos = e.pageX;
    	yMousePos = e.pageY;
	}
	window.status="x:" + xMousePos + " y:" + yMousePos;
	//setInnerHTML('debug',xMousePos + "," + yMousePos)
}

function MoveWindow(e) {
	captureMousePosition(e);	
	if (!xStartPos) {
		xStartPos = xMousePos;
		yStartPos = yMousePos;
	}
    if (__window_selected!=null) {
    	x = parseInt(__window_selected.style.left) + xMousePos - xStartPos;
    	y = parseInt(__window_selected.style.top) + yMousePos - yStartPos;
   		__window_selected.style.left = x + "px";
		__window_selected.style.top = y + "px";
    }
	xStartPos = xMousePos;
	yStartPos = yMousePos;
}


function StartMoveWindow(id) {
	var vExplorer = isExplorer();
	if (vExplorer==6) id=id+"_parent";
	
	//RaiseWindow(id);
	xStartPos = null;
	__window_selected = document.getElementById(id);
	if (document.layers) { // Netscape
	    document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	} else if (document.all) { // Internet Explorer
	    document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	} else if (document.getElementById) { // Netcsape 6
    	document.onmousemove = MoveWindow;
    	document.onmouseup = StopMoveWindow;
	}
}

var ic=0;
function testScroll(e) {
	setInnerHTML('debug',ic + ":=" + getHScrollPos() + "," + getVScrollPos() + "  " + getDocumentWidth() + "x" + getDocumentHeight());
	ic++;
}

function StopMoveWindow(id) {
    document.onmousemove = null;
    document.onmouseup = null;
	__window_selected = null;
}



function CreateURLWindow(id,x,y,url) {
	activeWindows=1;
	updateFlashHeaderWindowMode('transparent');

	if(isExplorer()>0){
		y += getVScrollPos();
	}
	
	var wwidth = getDocumentWidth();
	var wheight = getDocumentHeight();
	
	var vExplorer = isExplorer();
	var cx = 0;
	var cy = 0;
	// This window will never be destroyed so decrement activeWindows
	CreateWindow(id + "bg","0px","0px",wwidth + "px",wheight + "px","","#000000","30");
	//if (vExplorer==6) CreateIFrame(id + "bg","0px","0px",wwidth + "px",wheight + "px","#000000","30");
	//else CreateWindow(id + "bg","0px","0px",wwidth + "px",wheight + "px","","#000000","30");
	if (vExplorer==6) {
		//CreateIEWindow(id,x + 'px',y + 'px',null,null,"",null,null);
		CreateWindow(id,x + 'px',y + 'px',null,null,"",null,null);
		//Vamos a ocultar todos los select visibles y ponerlos en un array.
		allSelects[id] = new Array();
		selects = document.getElementsByTagName('select');
		for (i=0;i<selects.length;i++) {
			if (selects[i].style.visibility!='hidden') {
				allSelects[id].push(selects[i]);
				selects[i].style.visibility='hidden';
			}
		}
	}
	else {
		CreateWindow(id,x + 'px',y + 'px',null,null,"",null,null);
	}
	ajax_call(id,url,null);
}


//********************************************
// pone una ventana en primer plano.
//--------------------------------------------
//
// @params:
//	id: id del elemento.
//
// @return: 
//
//********************************************
function RaiseWindow(id) {
	var windowdiv = document.getElementById(id);
	zi = __zIndex++;
	windowdiv.style.zIndex=zi;
}



//********************************************
// destruye una ventana creada con CreateWindow.
//--------------------------------------------
//
// @params:
//	id: id de la div contenedora de la ventana.
//
// @return: 
//
//********************************************
function DestroyWindow(id) {
	var abody = document.getElementsByTagName("body");
	var vExplorer = isExplorer();
	
	var div = null;
	if (abody.length>=1) div = abody[0];
	if (div!=null) {
		var windowdiv;
		
		windowdiv = document.getElementById(id+"_parent");
		
		if (windowdiv!=null) {
			purge(windowdiv);
			div.removeChild(windowdiv);
		}
		
		windowdiv = document.getElementById(id);
		if (windowdiv!=null) {
			purge(windowdiv);
			div.removeChild(windowdiv);
		}
		
		var windowbg = document.getElementById(id + "bg");
		if (windowbg!=null) {
			if(activeWindows==1){
				updateFlashHeaderWindowMode('window');
				activeWindows=0;
			}
			purge(windowbg);
			div.removeChild(windowbg);
		}
		
		var windowiframe = document.getElementById(id + "_parent");
		if (windowiframe!=null) {
			purge(windowiframe);
			div.removeChild(windowiframe);
		}
		
	}
	//Manda el foco al ultimo foco conocido.
	setFocusOn(lastFocus);
	//Vuelve a mostrar los select que ocultamos en CreateWindow.
	if (vExplorer<=6 && vExplorer>3) {
		if (allSelects[id]) {
			len = allSelects[id].length;
			for (i=0;i<len;i++) {
				select = allSelects[id].pop();
				select.style.visibility='visible';
			}
			allSelects[id] = null;
		}
	}
}


//********************************************
// establece el estado de visibilidad de un elemento
// usando el id.
//--------------------------------------------
//
// @params:
//	id: id del elemento.
//	visible: true | false.
//
// @return: 
//
//********************************************
function Show(id,visible) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (visible) {
		obj.style.visibility = "visible";
	} else {
		obj.style.visibility = "hidden";
	}
	//Les pone la misma visibilidad que la capa que los contiene.
	vExplorer = isExplorer();
	if (vExplorer<=6 && vExplorer>3) {
		selects = obj.getElementsByTagName('select');
		for (i=0;i<selects.length;i++) selects[i].style.visibility =obj.style.visibility;
	}
}

function Resize(id,w,h) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (w>0) obj.style.width=w+ "px";
	if (h>0) obj.style.height=h+ "px";
}

function ShowAndResize(id,visible,w,h) {
	Show(id,visible);
	Resize(id,w,h);
}

function SwapShow(id) {
	obj = document.getElementById(id);
	if (obj==null) return;
	if (obj.style.visibility=="visible") {
		Show(id,false);
	} else {
		Show(id,true);
	}
}

//Pequeño workaround para devolver el foco despues de un popup 
//al ultimo objeto sobre el que hicimos un setFocus.
var lastFocus;

function setFocusOn(id) {
	obj = document.getElementById(id);
	if (obj==null) return;
	obj.focus();
	lastFocus = id;
}





//********************************************
// limpia espacios al principio y al final
// de una cadena.
//--------------------------------------------
//
// @params:
//	str: la cadena a limpiar.
//
// @return: 
//	la cadena modificada.
//
//********************************************
function cleanSpaces(str) {
	//pendiente
}


function setFlashVar(flashid,varname,varvalue) {
	fl = document.getElementById("mz" + flashid);
	if (!fl) fl = document.getElementById(flashid);
 	if (fl!=null) fl.SetVariable(varname,varvalue);
}



var chatWindowStatus = 0;
function setChatWindowStatus(status) {
	chatWindowStatus = status;
}

var chatWindow = null;
function openChat(para,roomid,solicitud) {
	if (chatWindowStatus==0) {
		var chatparams = '';
		if(para != '' ){
			chatparams = '?para=' + para + '&roomid=' + roomid + '&solicitud=' + solicitud; 
		}
		var url = "wmiscomchat.php" + chatparams;
		//var url = "testresize.php" + chatparams;
		chatWindow = window.open(url, 'chat', 'height=562,width=552,scrollbars=0,resizable=1');
		if(!chatWindow.opener) chatWindow.opener=self;
		if(window.focus){
			chatWindow.focus();
		}
	} else {
		ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
        //if (isFirefox()) {
        //    fh = document.getElementById('mzFlashHead');
        //} else fh = document.getElementById('FlashHead');
		//fh.openPrivateChat(para,roomid,solicitud);
		//url = "php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid;
		//alert(url);
		//ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
	}
}

function openChatFromFlash(para,roomid,solicitud) {
	window.opener.ajax_call("__","php/lanzachatprivado.php?para=" + para + "&solicitud=" + solicitud + "&roomid=" + roomid,null);
}


function reloadChat() {
	window.location.reload();
}

function showPopUp(windowname,url) {
	CreateURLWindow(windowname,
					0,
					0,
					url);
}

function setWindowToFullScreen(windowname) {
	wn = document.getElementById(windowname);
	wn.style.position='absolute';
	wn.style.left='0px';
	wn.style.top='0px';
	wn.style.width = getDocumentWidth() + "px";
	wn.style.height = getDocumentHeight() + "px";
	wn.style.width="100%";
	wn.style.height="100%";
}

function showInfoPopUp(title,msg) {
	CreateURLWindow("infowindow",
					getWindowWidth()/2-100,
					getWindowHeight()/2-100,
					"php/mostrarpopupinfo.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg));
}

function showConfirmationPopUp(title,msg,yeslink,nolink) {
	CreateURLWindow("confirmationwindow",
					getWindowWidth()/2-100,
					getWindowHeight()/2-100,
					"php/mostrarpopupconfirmation.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg) + "&ylink="+yeslink+"&nlink=" + nolink);
}

function showWarningPopUp(title,msg,onclose){
	CreateURLWindow("warningwindow",
					getWindowWidth()/2-175,
					getWindowHeight()/2-150,
					"php/mostrarpopupaviso.php?ttl=" + encodeURI(title) + 
					"&msg=" + encodeURI(msg) + "&onclose=" + onclose);
}

//********************************************
// Funcion para en los submenus verticales.
// Resalta el fondo del submenu donde este el cursor.
//--------------------------------------------
//
// @params:
//	H: elemento donde se ha situado el cursor.
//
//********************************************
function fhover(H){
if(H.className.indexOf("HoverBGColor")>=0)
H.className=H.className.replace("HoverBGColor ","");
else H.className="HoverBGColor "+H.className;
}

//********************************************
// Funciones de la primera version del portal.
// Funciones utilizadas para mostrar y ocultar textos con los links de "comprimir todo" y "expandir todo".
function activa(tipo)
{
	if (activado!="") document.getElementById(activado).style.display="none";
	if (activado!=tipo)
	{
		document.getElementById(tipo).style.display="";
		activado=tipo;
	}
	else activado="";
}

function activa_sub(tipo,enlace)
{
	if (document.getElementById(tipo).style.display=='none')
	{ 
		document.getElementById(tipo).style.display="";
		// muestra en la subseccion el link comprimir todo
		
		var splittedId = tipo.split("_");
		subid = splittedId[0] + "_" + splittedId[1] + "_" + splittedId[2];
		
		document.getElementById(subid).style.display="";
	}
	else 
	{
		document.getElementById(tipo).style.display="none";
		
		var splittedId = tipo.split("_");
		subid = splittedId[0] + "_" + splittedId[1] + "_" + splittedId[2];
		
		document.getElementById(subid).style.display="";
		subspans=document.getElementsByName(subid);
		subdisplay="none";
		for(i=0;i<subspans.length;i++)
		{
			if (subspans[i].style.display=="") subdisplay="";
		}
		document.getElementById(subid).style.display=subdisplay;
	}
	if (document.getElementById(enlace).className=='expandirbw') document.getElementById(enlace).className="comprimirbw";
		else document.getElementById(enlace).className="expandirbw";
}

function comprimir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="none";
		if (valor2==enlace) v_doc[i].className="expandirbw";
	}
}

function expandir_todo(tipo,enlace)
{
	v_doc=document.getElementsByTagName('*');
	for(i=0;i<v_doc.length;i++)
	{
		tam=tipo.length;
		valor=v_doc[i].id.substring(0,tam);
		tam2=enlace.length;
		valor2=v_doc[i].id.substring(0,tam2);
		if (valor==tipo) v_doc[i].style.display="";
		if (valor2==enlace) v_doc[i].className="comprimirbw";
	}
}

function ocultar(tipo)
{
	document.getElementById(tipo).style.display="none";
	activado="";
}

//Comprueba el formato del correo
function verifica_mail(t_mail)
{
	if ((t_mail.lastIndexOf(" ")!=-1) || (t_mail.lastIndexOf("@")==-1) || (t_mail.lastIndexOf(".")<=(t_mail.lastIndexOf("@")+1)) || (t_mail.lastIndexOf(".")==(t_mail.length-1))) return false;
		else return true;
}

var javascriptNewMessage = "";
function OnNewMessage() {
	eval(javascriptNewMessage);
}

var javascriptNewMobi = "";
function OnNewMobi() {
	eval(javascriptNewMobi);
}

function show_div(tipo)
{	
	if(document.getElementById(tipo)) document.getElementById(tipo).style.display="block";
}

function hide_div(tipo)
{
	if(document.getElementById(tipo)) document.getElementById(tipo).style.display="none";
}

function ifsetdisplay(divtipo,divboton)
{
	if (document.getElementById(divtipo).style.display=='none')
	{ 
		document.getElementById(divboton).style.display="block";
	}
	else 
	{	
		document.getElementById(divboton).style.display="none";
	}
}


function compareOptionText(a,b) {

	// textual comparison
	return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;

}

function sortOptions(list) {

	var items = list.options.length;

	// create array and make copies of options in list
	var tmpArray = new Array(items);

	for ( i=0; i<items; i++ )
		tmpArray[i] = new Option(list.options[i].text,list.options[i].value);

	// sort options using given function
	tmpArray.sort(compareOptionText);
	
	// make copies of sorted options back to list
	for ( i=0; i<items; i++ )
		list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);

}

function onCloseSession() {
	document.location='login.php';	
}

function sendVerificationEmail(email, alias, signupDate, lang){
	var response_container = document.getElementById('verification-email-sent');
	response_container.innerHTML = "<img src='images/common/popups/h-ajax-loading.gif' border='0' />";
	
	//ajax_eval_response("php/usuariodatos_form.php?cmd=verification-email&email="+email, "email=" + email + "&alias=" + alias + "&signupDate=" + signupDate + "&lang=" + lang);
	
	new Ajax.Request("php/email_verify_email_address.php",{
			method: 'get',
			parameters: {'email':email, 'alias':alias, 'signupDate':signupDate, 'lang':lang},
			onSuccess: function(transport){
				response_container.innerHTML = transport.responseText; 
			}
		});
}

function externalLinks() {
	if (!document.getElementsByTagName) {
		return;
	}
	var anchors = document.getElementsByTagName("a");
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("rel")) {
			var rel = anchor.getAttribute("rel");
			var external = false;
			if (rel.indexOf(" ") > 0) {
				while (rel.indexOf(" ") > 0 && external == false) {
					if (rel.substr(0, rel.indexOf(" ")) == "external") {
						external = true;
					}
					rel = rel.substr(rel.indexOf(" ") + 1, rel.length - rel.indexOf(" ") + 1);
				}
			}
			if (rel == "external") {
				external = true;
			}
			if (anchor.getAttribute("href") && external == true) {
				anchor.target = "_blank";
			}
		}
	}
	return;
}

//********************************************
//
//	Copyright Mobifriends S.L. 2007
//	
//	programador: Javier Velasco Gonzalez	
//
//********************************************

var error_page;
var errors;
var errorPages;

errors = new Array();
errorPages = new Array();

var sLoadingMessage = "string" === typeof sLoadingMessageTranslated ? sLoadingMessageTranslated:"Loading...";
var bLoading = false;
var sLoadingOpacity = "80";

function  html_cargador() {
	/*
	var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
	return "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='"+protocol+"fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=			8,0,0,0' width='100%' height='32' align='middle'>" + 
			"<param name='allowScriptAccess' value='sameDomain' />"+
			"<param name='wmode' value='transparent' /><param name='movie' value='" + ajaxLoaderClip + "' />"+
			"<param name='quality' value='high' /><param name='scale' value='noscale' />"+
			"<embed src='" + ajaxLoaderClip + "' scale='noscale' quality='high' width='100%' height='32' " + 
			"align='middle' wmode='transparent' allowScriptAccess='sameDomain' " + 
   			"type='application/x-shockwave-flash' pluginspage='"+protocol+"www.adobe.com/go/getflashplayer' />" + 
			"</object>";
	*/
}

//********************************************
// hace una llamada remota a un script copiando 
// la respueta dentro del elemento id.
//--------------------------------------------
//
// @params:
//	id: attributo id del elemento que recibe la respueta.
//	url: url del script en el servidor.
//	func: funcion que recibe los errores, si se omite 
//		se hace una llamada a las funciones generales
//		para el tratamiento de errores (ver ajax_on_error).
//
// @return: 
//
//********************************************
function ajax_call(id,url, func,disableloader) {
	var request;
	var error_func = func;
	
	if(typeof XMLHttpRequest!='undefined') {
		request = new XMLHttpRequest();
	} else {
		if (Number(navigator.appVersion.substr(0,3))>=5) 
			request = new ActiveXObject('Msxml2.XMLHTTP');
		else
			request = new ActiveXObject('Microsoft.XMLHTTP');
	}

	if (request) {
		request.onreadystatechange = function () {
			if(request.readyState == 4)
			{
				if (request.status == 200) {
					if (!disableloader) {
						DestroyWindow("backgroundloader");
						DestroyWindow("ajaxloader");
					}
					element = document.getElementById(id);
					if (element!=null) element.innerHTML = request.responseText;
					/* ejecuta los scripts dentro del html */
					var startPos=0;
					var endPos=0;
					var script;
					var uchtml = request.responseText.toUpperCase();
					startPos = 0;	
					do {
						startPos = uchtml.indexOf("<SCRIPT",startPos);
						if (startPos<0) break;
						startPos = 1 + uchtml.indexOf(">",startPos);
						endPos = uchtml.indexOf("</SCRIPT>",startPos);
						script =request.responseText.substr(startPos,endPos-startPos);
						if (window.execScript){
							window.execScript(script);
						}else{
							eval(script);
						}
						startPos = endPos+1;
					} while(true);	
				} else {
				   if (error_func) {
				   		error_func(request.status);			   	
				   } else {
				   		for (var i in errors) {
        					if (errors[i]==request.status) {
        						//alert(errorPages[i]);
        						document.location = errorPages[i];
        					}
			   			}
				   }
				}
			}
		}
		if (!disableloader) {
			var wwidth = getWindowWidth();
			var wheight = getWindowHeight();
			CreateWindow("backgroundloader","0px","0px",wwidth + "px",wheight + "px","",null,"30");
			CreateWindow("ajaxloader","0px","0px",wwidth + "px","32px",sLoadingMessage,null,sLoadingOpacity,"loading-window");
		}
		request.open("GET",url,true)
		request.send(null);
	}
}


//********************************************
// envia el contenido de un form copiando 
// la respueta dentro del elemento id.
//--------------------------------------------
//
// @params:
//	id: attributo id del elemento que recibe la respuesta.
//	url: url del script en el servidor.
//	func: funcion que recibe los errores, si se omite 
//		se hace una llamada a las funciones generales
//		para el tratamiento de errores (ver ajax_on_error).
//
// @return: 
//
//********************************************
function ajax_submit_form(id,formName,url, func) {
	var request;
	var form;
	var formdata="";
	var fields;
	var error_func = func;
	
	form = document.getElementById(formName);
	if(typeof XMLHttpRequest!='undefined') {
		request = new XMLHttpRequest();
		fields = form.elements;
	} else {
		version = isExplorer();
		if (version>=5) 
			request = new ActiveXObject('Msxml2.XMLHTTP');
		else
			request = new ActiveXObject('Microsoft.XMLHTTP');
		if (version>=5 && version<7) fields = form.all;

	}
	
	for (i in fields)
	{
		var element = fields[i];
		if (element!=null && element.tagName!=null) {
			if (element.tagName=="SELECT" || element.tagName=="INPUT" || element.tagName=="TEXTAREA") {
				if (element.type=="checkbox" || element.type=="radio") {
					if (element.checked==true) formdata+=element.name + "=" + element.value + "&";
				} else formdata+=element.name + "=" + element.value + "&";
			}
		}
	}
	
	if (request) {
		request.onreadystatechange = function () {
			if(request.readyState == 4)
			{
				if (request.status == 200) {
					
					if(bLoading){
						DestroyWindow("backgroundloader");
						DestroyWindow("ajaxloader");
					}
					
					element = document.getElementById(id);
					//Si pusieramos cuidado en no borrar divs no tendria que hacer esto.
					if (element) element.innerHTML = request.responseText;
					/* ejecuta los scripts dentro del html */
					var startPos=0;
					var endPos=0;
					var script;
					var uchtml = request.responseText.toUpperCase();
					startPos = 0;	
					do {
						startPos = uchtml.indexOf("<SCRIPT",startPos);
						if (startPos<0) break;
						startPos = 1 + uchtml.indexOf(">",startPos);
						endPos = uchtml.indexOf("</SCRIPT>",startPos);
						script =request.responseText.substr(startPos,endPos-startPos);
						if (window.execScript){
							window.execScript(script);
						}else{
							eval(script);
						}
						startPos = endPos+1;
					} while(true);	
				} else {
				   if (error_func) {
				   		error_func(request.status);			   	
				   } else {
				   		for (var i in errors) {
        					if (errors[i]==request.status) {
        						//alert(errorPages[i]);
        						document.location = errorPages[i];
        					}
			   			}
				   }
				}
			}
		}

		if(bLoading){
			var wwidth = getWindowWidth();
			var wheight = getWindowHeight();
			CreateWindow("backgroundloader","0px","0px",wwidth + "px",wheight + "px","",null,"30");
			CreateWindow("ajaxloader","0px","0px",wwidth + "px","32px",sLoadingMessage,null,sLoadingOpacity,"loading-window");
		}
			
		request.open("POST",url,true)
		request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		request.send(formdata);
	}
}


//********************************************
// llama al ajax_submit_form, cuando el usuario 
// aprieta el Enter
//--------------------------------------------
//
// @params: (el evento y los parametros de ajax_submit_form)
//
// @return: 
//
//********************************************
function ienter_submit_form(evento, id,formName,url, func) {
	var iAscii;
	if (evento.keyCode) iAscii = evento.keyCode; 
		else if (evento.which) iAscii = evento.which; 
			else return false; 
	if (iAscii == 13) ajax_submit_form(id,formName,url, func); 
	return true; 
}


//********************************************
// envia el contenido de un form copiando 
// ejecutando la respueta como un script.
//--------------------------------------------
//
// @params:
//	formName: id del formulario.
//	url: url del script en el servidor.
//	func: funcion que recibe los errores, si se omite 
//		se hace una llamada a las funciones generales
//		para el tratamiento de errores (ver ajax_on_error).
//
// @return: 
//
//********************************************
function ajax_eval_form(formName,url, func,disableloader) {
	var request;
	var form;
	var formdata="";
	var fields;
	var error_func = func;
	var scrWidth,scrHeight;
	

	form = document.getElementById(formName);
	if (form==null) return;
	fields = form.elements;
	if(typeof XMLHttpRequest!='undefined') {
		request = new XMLHttpRequest();
	} else {
		version = isExplorer();
		if (version>=5) 
			request = new ActiveXObject('Msxml2.XMLHTTP');
		else
			request = new ActiveXObject('Microsoft.XMLHTTP');
		if (version>=5 && version<7) fields = form.all;
		
	}

	for (i in fields)
	{
		var element = fields[i];
		if (element!=null && element.tagName!=null) {
			if (element.tagName=="SELECT" || element.tagName=="INPUT" || element.tagName=="TEXTAREA") {
				if (element.type=="checkbox" || element.type=="radio" ) {
					if (element.checked==true) formdata+=element.name + "=" + element.value + "&";
				} else formdata+=element.name + "=" + element.value + "&";
			}
		}
	}
	
	if (request) {
		request.onreadystatechange = function () {
			if(request.readyState == 4)
			{
				if (request.status == 200) {
					if (!disableloader) {
						DestroyWindow("backgroundloader");
						DestroyWindow("ajaxloader");
					}
					if (window.execScript){
						window.execScript(request.responseText);
					}else{
						eval(request.responseText);
					}
				} else {
				   if (error_func) {
				   		error_func(request.status);			   	
				   } else {
				   		for (var i in errors) {
        					if (errors[i]==request.status) {
        						//alert(errorPages[i]);
        						document.location = errorPages[i];
        					}
			   			}
				   }
				}
			}
		}
		
		if (!disableloader) {
			var wwidth = getWindowWidth();
			var wheight = getWindowHeight();
			CreateWindow("backgroundloader","0px","0px",wwidth + "px",wheight + "px","",null,"30");
			CreateWindow("ajaxloader","0px","0px",wwidth + "px","32px",sLoadingMessage,null,sLoadingOpacity,"loading-window");		
		}
		request.open("POST",url,true);
		request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
		request.send(formdata);
	}
}


//********************************************
// añade una funcion envia el contenido de un form copiando 
// la respueta dentro del elemento id.
//--------------------------------------------
//
// @params:
//	id: attributo id del elemento que recibe la respuesta.
//	url: url del script en el servidor.
//	func: funcion que recibe los errores, si se omite 
//		se hace una llamada a las funciones generales
//		para el tratamiento de errores (ver ajax_on_error).
//
// @return: 
//
//********************************************
function ajax_on_error(status,url) {
	errors.push(status);
	errorPages.push(url);
}

//********************************************
// registra una pelicula para ser mostrada 
// mientras se esperan datos en una peticion AJAX.
//--------------------------------------------
//
// @params:
//	clipname: nombre del movieclip de flash.
//
// @return: 
//
//********************************************
function ajax_register_loader(clipname) {
	// ajaxLoaderClip = clipname;
	bLoading = true;
}

function ajax_eval_response(url, params) {
	var request;
	var version;

	if(typeof XMLHttpRequest!='undefined') {
		request = new XMLHttpRequest();
	} else {
		version = isExplorer();
		if (version>=5) 
			request = new ActiveXObject('Msxml2.XMLHTTP');
		else
			request = new ActiveXObject('Microsoft.XMLHTTP');		
	}
	
	if (request) {
		request.onreadystatechange = function () {
			if(request.readyState == 4){
				if (request.status == 200) {
					if (window.execScript){
						window.execScript(request.responseText);
					}else{
						eval(request.responseText);
					}
				}
			}
		}
		
		request.open("POST",url,true);
		request.send(params);
	}
}
