var fondoDialogo = 
{
	capa: null,
	animOpacidad: null,
	funcionCerrarConClick: null,
	funcionCentrar: null,
	funcionCerrado: null,
	
	abrir: function (cerrarConClick, cerrado)
	{
		if (this.capa == null)
		{
			this.capa = Builder.node ("div", {className: "fondoDialogo", style: "display: none;"});
			document.body.appendChild (this.capa);
		}
		
		this.capa.style.display = "block";
		if (this.animOpacidad != null) this.animOpacidad.cancel();
		this.animOpacidad = new Effect.Opacity (this.capa, {duration: 0.3, from: 0, to: 0.6});
		this.centrar ();
		
		if (cerrarConClick)
		{
			this.funcionCerrarConClick = this.cerrar.bind (this);
			Event.observe (this.capa, "mouseup", this.funcionCerrarConClick);
		}

		this.funcionCentrar = this.centrar.bind (this);
		this.funcionCerrado = cerrado? cerrado: null;
		Event.observe (window, "resize", this.funcionCentrar);
		Event.observe (window, "scroll", this.funcionCentrar);
	},
	
	cerrar: function ()
	{
		if (this.funcionCerrarConClick != null)
		{
			Event.stopObserving (this.capa, "mouseup", this.funcionCerrarConClick);
			this.funcionCerrarConClick = null;
		}
		Event.stopObserving (window, "resize", this.funcionCentrar);
		Event.stopObserving (window, "scroll", this.funcionCentrar);
		
		if (this.funcionCerrado != null) this.funcionCerrado ();
		this.animOpacidad.cancel();
		this.animOpacidad = new Effect.Opacity (this.capa, {duration: 0.3, from: 0.6, to: 0, afterFinish: function()
		{
			fondoDialogo.capa.style.display = "none";
		}});
	},
	
	centrar: function ()
	{
		var posicion = document.viewport.getScrollOffsets ();
		var tamano = document.viewport.getDimensions ();
		
		with (this.capa.style)
		{
			left = posicion.left + "px";
			top = posicion.top + "px";
			width = tamano.width + "px";
			height = tamano.height + "px";
		}
	}
};


var dialogoBase = Class.create
({
	ancho: 450,
	alto: 100,
	
	ventana: null,
	abierto: false,

	cabecera: null,
	contenido: null,
	icono: null,
	texto: null,
	input: null,
	botones: null,
	botonAceptar: null,
	botonCancelar: null,
	textoBotonAceptar: null,
	textoBotonCancelar: null,

	funcionCentrar: null,
	funcionTeclaPulsada: null,

	mostrarCancelar: false,
	modoPrompt: false,

	iniciar: function (texto, parametros)
	{
		this.leerParametros (parametros);
		this.parametros.texto = texto;
	},
	
	alert: function (texto, parametros)
	{
		this.iniciar (texto, parametros);
		this.modoPrompt = false;
		this.mostrarCancelar = false;
		if (this.ventana == null) this.construir ();
		this.actualizarElementos ();
		this.abrir ();
	},

	confirm: function (texto, parametros)
	{
		this.iniciar (texto, parametros);
		this.modoPrompt = false;
		this.mostrarCancelar = true;
		if (this.ventana == null) this.construir ();
		this.actualizarElementos ();
		this.abrir ();
	},

	prompt: function (texto, parametros)
	{
		this.iniciar (texto, parametros);
		this.modoPrompt = true;
		this.mostrarCancelar = true;
		if (this.ventana == null) this.construir ();
		this.actualizarElementos ();
		this.abrir ();
	},
	
	leerParametros: function (parametros)
	{
		if (this.parametros == null) this.parametros = {};
		if (parametros == null) parametros = {};
		this.parametros.titulo = parametros.titulo? parametros.titulo: "Viciojuegos.com";
		this.parametros.icono = parametros.icono? parametros.icono: "";
		this.parametros.textoAceptar = parametros.textoAceptar? parametros.textoAceptar: "Aceptar";
		this.parametros.textoCancelar = parametros.textoCancelar? parametros.textoCancelar: "Cancelar";
		this.parametros.funcionAceptar = parametros.aceptado? parametros.aceptado: null;
		this.parametros.funcionCancelar = parametros.cancelado? parametros.cancelado: null;
		this.parametros.funcionCerrar = parametros.cerrado? parametros.cerrado: null;
		this.parametros.textoPredeterminado = parametros.textoPredeterminado? parametros.textoPredeterminado: "";
	},
	
	construir: function ()
	{
		this.ventana = Builder.node ("div", {className: "ventanaDialogo", style: "width: " + (this.ancho+80) + "px; height: " + (this.alto+112) + "px"},
		[
			Builder.node ("div", {className: "borde si"}),
			Builder.node ("div", {className: "borde sc", style: "width: " + this.ancho + "px"}),
			Builder.node ("div", {className: "borde sd"}),
			Builder.node ("div", {className: "bordeV ci", style: "width: " + ((this.ancho+80) / 2) + "px; height: " + (this.alto+30) + "px"}),
			Builder.node ("div", {className: "marcoContenido", style: "width: " + (this.ancho+40) + "px; height: " + (this.alto+72) + "px"},
			[
				this.cabecera = Builder.node ("h2", {className: "fondoPrimario colorSecundario degradado"}),
				this.contenido = Builder.node ("div", {className: "contenido", style: "width: " + this.ancho + "px; height: " + this.alto + "px"})
			]),
			Builder.node ("div", {className: "bordeV cd", style: "width: " + ((this.ancho+80) / 2) + "px; height: " + (this.alto+30) + "px"}),
			Builder.node ("div", {className: "borde ii"}),
			Builder.node ("div", {className: "borde ic", style: "width: " + this.ancho + "px"}),
			Builder.node ("div", {className: "borde id"}),
		]);
		this.generarContenido ();
		document.body.appendChild (this.ventana);
	},
	
	generarContenido: function ()
	{
		this.icono = Builder.node ("div", {className: "icono", style: "height: " + this.alto + "px"});
		this.texto = Builder.node ("p");
		this.input = Builder.node ("input", {type: "text", className: "formulario"});
		this.botones = Builder.node ("div", {className: "botones", style: "width: " + this.ancho + "px"},
		[
			this.botonCancelar = Builder.node ("a", {className: "botonTuneado"}),
			this.botonAceptar = Builder.node ("a", {className: "botonTuneado"})
		]);
		
		tunearEnlace (this.botonCancelar);
		tunearEnlace (this.botonAceptar);
		this.textoBotonCancelar = this.botonCancelar.down (".c");
		this.textoBotonAceptar = this.botonAceptar.down (".c");
		if (this.textoBotonCancelar == null) this.textoBotonCancelar = this.botonCancelar;
		if (this.textoBotonAceptar == null) this.textoBotonAceptar = this.botonAceptar;
		
		this.contenido.appendChild (this.icono);
		this.contenido.appendChild (this.texto);
		this.contenido.appendChild (this.input);
		this.contenido.appendChild (this.botones);
	},
	
	actualizarElementos: function ()
	{
		this.cabecera.innerHTML = this.parametros.titulo;
		this.textoBotonAceptar.innerHTML = this.parametros.textoAceptar;
		if (this.mostrarCancelar)
		{
			this.textoBotonCancelar.innerHTML = this.parametros.textoCancelar;
			this.botonCancelar.style.visibility = "visible";
		}
		else this.botonCancelar.style.visibility = "hidden";
		if (this.parametros.icono)
		{
			this.icono.style.backgroundImage = "url(" + rutaImagenes + "dialogos/" + this.parametros.icono + ")";
			this.icono.style.display = "block";
			Element.addClassName (this.texto, "conIcono");
		}
		else
		{
			this.icono.style.display = "none";
			Element.removeClassName (this.texto, "conIcono");
		}
		this.texto.innerHTML = this.parametros.texto;
		if (this.modoPrompt)
		{
			this.input.value = this.parametros.textoPredeterminado;
			Element.addClassName (this.texto, "conInput");
			this.input.style.display = "block";
		}
		else
		{
			this.input.style.display = "none";
			Element.removeClassName (this.texto, "conInput");
		}
	},
	
	abrir: function ()
	{
		this.ventana.style.display = "block";
		this.centrar ();
		fondoDialogo.abrir ();
		this.abierto = true;

		this.funcionCentrar = this.centrar.bind (this);
		this.funcionTeclaPulsada = this.teclaPulsada.bindAsEventListener (this);
		Event.observe (window, "resize", this.funcionCentrar);
		Event.observe (window, "scroll", this.funcionCentrar);
		Event.observe (document, "keyup", this.funcionTeclaPulsada);
		Event.observe (this.botonAceptar, "click", this.aceptarPulsado.bind (this));
		if (this.mostrarCancelar) Event.observe (this.botonCancelar, "click", this.cancelarPulsado.bind (this));

		if (this.modoPrompt)
		{
			this.input.style.width = (this.texto.offsetWidth-6) + "px";
			this.input.focus();
			this.input.select();
		}
		else this.ventana.focus();
	},
	
	cerrar: function ()
	{
		Event.stopObserving (window, "resize", this.funcionCentrar);
		Event.stopObserving (window, "scroll", this.funcionCentrar);
		Event.stopObserving (document, "keyup", this.funcionTeclaPulsada);
		Event.stopObserving (this.botonAceptar, "click");
		if (this.mostrarCancelar) Event.stopObserving (this.botonCancelar, "click");
		this.ventana.style.display = "none";
		fondoDialogo.cerrar ();
	},

	centrar: function ()
	{
		var posicion = document.viewport.getScrollOffsets ();
		var tamano = document.viewport.getDimensions ();
		
		with (this.ventana.style)
		{
			left = ((tamano.width - this.ventana.offsetWidth) / 2) + "px";
			top = (posicion.top + ((tamano.height - this.ventana.offsetHeight) / 2)) + "px";
		}
	},
	
	teclaPulsada: function (event)
	{
		var tecla = (window.event) ? event.keyCode : event.which;
		if (tecla==27)
		{
			if (this.mostrarCancelar) this.cancelarPulsado ();
			else this.aceptarPulsado ();
		}
		else if (tecla==13) this.aceptarPulsado ();
	},
	
	aceptarPulsado: function ()
	{
		this.cerrar ();
		if (this.parametros.funcionAceptar)
		{
			if (this.modoPrompt) this.parametros.funcionAceptar (this.parametros.textoPredeterminado, this.input.value);
			else this.parametros.funcionAceptar();
		}
	},
	
	cancelarPulsado: function ()
	{
		this.cerrar ();
		if (this.parametros.funcionCancelar)
		{
			if (this.modoPrompt) this.parametros.funcionCancelar (this.parametros.textoPredeterminado, this.input.value);
			else this.parametros.funcionCancelar();
		}
	}
});

var marcaAguaTexto = Class.create
({
	input: null,
	marcaAgua: "",
	
	initialize: function (input)
	{
		this.input = input;
		this.marcaAgua = this.input.title;
		with (this.input)
		{
			if (value == "" || value == this.marcaAgua)
			{
				value = title;
				Element.addClassName (this.input, "marcaAguaVacio");
			}
			else Element.addClassName (this.input, "marcaAguaNormal");
		}
		Event.observe (this.input, "focus", this.focus.bind(this));
		Event.observe (this.input, "blur", this.blur.bind(this));
	},
	
	focus: function ()
	{
		if (this.input.value == this.marcaAgua)
		{
			this.input.removeClassName ("marcaAguaVacio");
			this.input.addClassName ("marcaAguaNormal");
			this.input.value = "";
		}
	},
	
	blur: function ()
	{
		if (this.input.value.length == 0) 
		{
			this.input.removeClassName ("marcaAguaNormal");
			this.input.addClassName ("marcaAguaVacio");
			this.input.value = this.marcaAgua; 
		}
	}
});


var selectTuneado = Class.create
({
	elemento: null,
    input: null,
    boton: null,
    lista: null,
	value: undefined,
	selectedIndex: -1,
	
	funcionChange: null,

    initialize: function (select)
	{
		this.selectedIndex = select.selectedIndex;
		value = select.value;
		this.elemento = Builder.node ("div", {className: "selectTuneado", style: "width: " + (select.offsetWidth - 2) + "px;"}, 
			[
				this.input = Builder.node ("input", {tabIndex: select.tabIndex, style: "width: " + (select.offsetWidth - 31) + "px;", readonly: "readonly"}),
				this.boton = Builder.node ("a")
			]
		);
		Element.setStyle (this.elemento, {"float": Element.getStyle(select, "float")});
		select.parentNode.insertBefore (this.elemento, select);
		
		this.funcionChange = select.onchange? select.onchange: null;
		
		var Yo = this;
		this.lista = new listaSelect (select, {ancho: this.elemento.offsetWidth, actualizar: function (seleccionado) {Yo.actualizar (seleccionado);}});
		this.input.value = this.lista.texto;
		Event.observe(this.input, "focus", this.desplegar.bind (this));
        Event.observe(this.boton, "click", this.desplegar.bind (this));
    },

	desplegar: function ()
	{
		var posicion = this.elemento.cumulativeOffset ();
		var vpPosicion = document.viewport.getScrollOffsets ();
		var vpTamano = document.viewport.getDimensions ();
		var top = 0;
		if (posicion.top + this.elemento.offsetHeight + this.lista.capa.offsetHeight >= vpPosicion.top + vpTamano.height) top = posicion.top - this.lista.capa.offsetHeight;
		else top = posicion.top + this.elemento.offsetHeight;
		this.lista.desplegar (posicion.left, top);
    },
	
	cerrar: function ()
	{
        this.lista.cerrar ();
    },
	
	actualizar: function (seleccionado)
	{
		this.input.value = this.lista.opciones[seleccionado].texto;
		this.value = this.lista.valor;
		this.selectedIndex = seleccionado;
		if (this.funcionChange != null) this.funcionChange (seleccionado);
    }
});


var listaSelect = Class.create (
{
	capa: null,
	scroll: null,
	slider: null,
	campo: null,
	opciones: null,
	elementos: null,
	seleccionado: -1,
	valor: "",
	texto: "",
	abierto: false,
	ultimoScroll: 0,
	ultimoSeleccionado: -1,
	maxOpciones: 15,
	
	funcionActualizar: null,
	eventoClickDocumento: null,
	eventoTeclado: null,
	eventoCancelar: null,
	
	initialize: function (select, config)
	{
		if (select.name != "undefined")
		{
			this.campo = Builder.node ("input", {type: "hidden", name: select.name, value: select.value});
			select.parentNode.insertBefore (this.campo, select);
		}
		
		this.opciones = new Array (select.options.length);
		this.elementos = new Array (select.options.length);
		for (var i=0; i<select.options.length; i++)
		{
			this.opciones[i] = {valor: select.options[i].value, texto: this.convertirCaracteres (select.options[i].innerHTML)};
			this.elementos[i] = Builder.node ("li", this.opciones[i].texto);
			Event.observe (this.elementos[i], "mouseover", this.seleccionar.bind (this, i));
			Event.observe (this.elementos[i], "click", this.enlaceClick.bind (this, i));
		}
		
		this.maxOpciones = config.maxOpciones || 15;
		this.capa = Builder.node ("div", {className: "listaSelect", style: "display: none; width: " + ((config.ancho || select.offsetWidth)-2) + "px;"});
		if (this.opciones.length > this.maxOpciones) this.scroll = Builder.node ("div", {className: "scroll", style: "width: " + ((config.ancho || select.offsetWidth)-13) + "px;"}, Builder.node ("ul", this.elementos));
		else this.scroll = Builder.node ("div", {className: "scroll", style: "width: " + ((config.ancho || select.offsetWidth)-2) + "px; height: auto;"}, Builder.node ("ul", this.elementos));
		this.capa.appendChild (this.scroll);
		if (this.opciones.length > this.maxOpciones) this.capa.appendChild (Builder.node ("div", {className: "slider"}, Builder.node ("div")));
		
		select.parentNode.insertBefore (this.capa, select);
		Element.remove (select);
		
		if (select.selectedIndex >= 0) this.seleccionar (select.selectedIndex);
		this.funcionActualizar = config.actualizar? config.actualizar: null;
		if (this.opciones.length > this.maxOpciones)
		{
			Event.observe (this.capa, "DOMMouseScroll", this.desplazarRueda.bindAsEventListener (this));
			Event.observe (this.capa, "mousewheel", this.desplazarRueda.bindAsEventListener (this));
		}
		else this.capa.style.height =  "auto";
	},
	
	convertirCaracteres: function (cadena)
	{
		var salida = cadena;
		salida = salida.replace (/&nbsp;/gi, "\u00A0");
		salida = salida.replace (/&gt;/gi, "\u003E");
		salida = salida.replace (/&lt;/gi, "\u003C");
		salida = salida.replace (/&amp;/gi, "\u0026");
		return salida;
	},
	
	desplegar: function (PosX, PosY)
	{		
		this.ultimoSeleccionado = this.seleccionado;
		this.capa.style.left = PosX + "px";
		this.capa.style.top = PosY + "px";
		this.capa.style.display = "block";
		this.capa.focus ();
		this.abierto = true;

		var Yo = this;
		if (this.slider == null && this.opciones.length > this.maxOpciones) this.slider = new Control.Slider (Element.select (this.capa, "div.slider div")[0], Element.select (this.capa, "div.slider")[0], {axis: "vertical", range: $R(0, this.scroll.scrollHeight - this.scroll.offsetHeight), onSlide: function (value) {Yo.scroll.scrollTop = value;}, onChange: function (value) {Yo.scroll.scrollTop = value;}});
		if (this.scroll.scrollTop != this.ultimoScroll) this.scroll.scrollTop = this.ultimoScroll;
		this.asegurarVisible ();
		this.eventoClickDocumento = this.documentClick.bindAsEventListener (this);
		this.eventoTeclado = this.capturarTeclado.bindAsEventListener (this);
		this.eventoCancelar = this.cancelarEvento.bindAsEventListener (this);
		Event.observe (document, "mousedown", this.eventoClickDocumento);
		Event.observe (document, "keyup", this.eventoTeclado);
		Event.observe (document, "keydown", this.eventoCancelar);
		Event.observe (document, "keypress", this.eventoCancelar);
	},
	
	cerrar: function ()
	{
		Event.stopObserving (document, "mousedown", this.eventoClickDocumento);
		Event.stopObserving (document, "keyup", this.eventoTeclado);
		Event.stopObserving (document, "keydown", this.eventoCancelar);
		Event.stopObserving (document, "keypress", this.eventoCancelar);
		this.eventoClickDocumento = null;
		this.eventoTeclado = null;
		this.eventoCancelar = null;
		if (this.ultimoSeleccionado != this.seleccionado) this.seleccionar (this.ultimoSeleccionado);
		this.ultimoScroll = this.scroll.scrollTop;
		this.capa.style.display = "none";
		this.abierto = false;
	},

	seleccionar: function (opcion)
	{
		if (this.seleccionado != opcion)
		{
			if (this.seleccionado >= 0) this.elementos[this.seleccionado].removeClassName ("seleccionado");
			this.elementos[opcion].addClassName ("seleccionado");
			this.seleccionado = opcion;
			this.valor = this.opciones[opcion].valor;
			this.texto = this.opciones[opcion].texto;
		}
	},
	
	actualizar: function ()
	{
		var actualizar = this.ultimoSeleccionado != this.seleccionado;
		this.ultimoSeleccionado = this.seleccionado;
		this.campo.value = this.valor;
		if (this.abierto) this.cerrar ();
		if (this.funcionActualizar != null && actualizar) this.funcionActualizar (this.seleccionado);
	},
	
	asegurarVisible: function ()
	{
		if (this.abierto)
		{
			var AltoElemento = this.elementos[0].offsetHeight;
			var Primero = Math.ceil (this.scroll.scrollTop / AltoElemento);
			var Ultimo =  Math.floor ((this.scroll.scrollTop + this.scroll.offsetHeight - AltoElemento) / AltoElemento);
			
			if (this.seleccionado < Primero) this.slider.setValue (this.seleccionado * AltoElemento);
			if (this.seleccionado > Ultimo) this.slider.setValue ((this.seleccionado - Math.floor (this.scroll.offsetHeight / AltoElemento)) * AltoElemento);
		}
	},
	
	desplazarRueda: function (event)
	{
		var delta = 0;
		if (!event) event = window.event;
		if (event.wheelDelta)
		{
			delta = event.wheelDelta / 120;
			//if (window.opera) delta = -delta;
		}
		else if (event.detail) delta = -event.detail / 3;

		if (delta) this.slider.setValueBy (delta * -20);
		if (event.preventDefault) event.preventDefault ();
		event.returnValue = false;
	},
	
	enlaceClick: function (opcion)
	{
		this.seleccionar (opcion);
		this.actualizar ();
	},
	
	documentClick: function (event)
	{
		if (!Event.element(event).descendantOf (this.capa)) this.cerrar ();
	},
	
	capturarTeclado: function (event)
	{
		switch (event.keyCode)
		{
			case 13:
				this.actualizar ();
				break;
				
			case 27:
				this.cerrar ();
				break;

			case 38:
				var opcion = this.seleccionado - 1;
				if (opcion < 0) opcion = this.opciones.length - 1;
				this.seleccionar (opcion);
				this.asegurarVisible ();
				break;
				
			case 40:
				var opcion = this.seleccionado + 1;
				if (opcion > this.opciones.length - 1) opcion = 0;
				this.seleccionar (opcion);
				this.asegurarVisible ();
				break;
				
			default:
				if (event.keyCode > 64 && event.keyCode < 91)
				{
					var opcion = this.seleccionado < this.opciones.length - 1? this.seleccionado + 1: 0;
					while (this.opciones[opcion].texto.toUpperCase().charCodeAt (0) != event.keyCode && opcion != this.seleccionado) opcion = opcion < this.opciones.length - 1? opcion + 1: 0;
					if (opcion != this.seleccionado)
					{
						this.seleccionar (opcion);
						this.asegurarVisible ();
					}
				}
		}
		this.cancelarEvento (event);
	},
	
	cancelarEvento: function (event)
	{
		if (event.preventDefault) event.preventDefault ();
		event.returnValue = false;
	}
});

var SelectorFecha = Class.create (
{
	campo: null,
	input: null,
	boton: null,
	fecha: null,
	mesActual: null,
	anoActual: null,
	calendario: null,
	botonMesAnterior: null,
	botonMesSiguiente: null,
	textoMes: null,
	dias: null,
	meses: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],

	initialize: function (input)
	{
		this.input = input;
		this.campo = Builder.node ("input", {type: "hidden", name: this.input.name});
		this.input.name = "";
		this.boton = Builder.node("a", {className: "BotonSelectorFecha"});
		this.fecha = new Date();
		
		this.InterpretarFecha();
		if (this.input.offsetWidth) this.input.style.width = (this.input.offsetWidth - 29)+"px";
		else if (this.input.style.width) this.input.style.width = (parseInt(this.input.style.width) - 29)+"px";
		var insercion = this.input.nextSibling;
		if (insercion) this.input.parentNode.insertBefore (this.boton, insercion);
		else this.input.parentNode.appendChild (this.boton);
		this.input.parentNode.insertBefore (this.campo, this.boton);
		
		Event.observe (this.input, "focus", this.MostrarFecha.bind(this));
		Event.observe (this.input, "blur", this.InterpretarFecha.bind(this));
		Event.observe (this.boton, "click", this.DesplegarCalendario.bind(this));
	},
	
	MostrarFecha: function ()
	{
		this.input.value = this.campo.value;
		this.input.select();
	},

	InterpretarFecha: function ()
	{
		var PartesFecha = this.input.value.match(/^(\d{1,2})(\/|)(\d{1,2})(\/|)(\d{4})$/);
		if (PartesFecha != null)
		{
			var Ok = true;
			var dia = PartesFecha[1];
			var mes = PartesFecha[3];
			var ano = PartesFecha[5];
			this.fecha.setTime (Date.parse(mes+"/"+dia+"/"+ano));
			this.ActualizarFecha();
		}
		else this.campo.value = this.input.value;
	},

	ActualizarFecha: function ()
	{
		this.campo.value = this.fecha.getDate() + "/" + (this.fecha.getMonth()+1) + "/" + this.fecha.getFullYear();
		this.input.value = this.fecha.toLocaleDateString();
	},

	ActualizarCalendario: function ()
	{
		var fecha = new Date(this.anoActual, this.mesActual, 1);
		var DiaSemana = fecha.getDay()==0?7: fecha.getDay();
		fecha.setTime (fecha.getTime()-((DiaSemana-1)*86400000));
		this.textoMes.innerHTML = this.meses[this.mesActual] + " " + this.anoActual;
		for (var i=0; i<this.dias.length; i++)
		{
			this.dias[i].EstablecerFecha (fecha);
			if (fecha.getMonth()!=this.mesActual) this.dias[i].EstablecerClase ("OtroMes");
			else if (fecha.getDate()==this.fecha.getDate() && fecha.getMonth()==this.fecha.getMonth() && fecha.getFullYear()==this.fecha.getFullYear()) this.dias[i].EstablecerClase ("Seleccionado");
			fecha.setTime (fecha.getTime()+86400000);
		}
	},

	CrearCalendario: function ()
	{
		var filas = new Array();
		this.dias = new Array(42);
		for (var i=0; i<this.dias.length; i++)
		{
			this.dias[i] = new CasillaCalendario();
			if (i%7==0) filas.push (Builder.node("tr"));
			filas[filas.length-1].appendChild (this.dias[i].celda);
			Event.observe (this.dias[i].enlace, "click", this.ClickCelda.bind(this, i));
		}

		this.calendario = Builder.node ("div", {className: "CalendarioDesplegable"}, [
			Builder.node ("div", {className: "SelectorMes"}, [
				this.botonMesAnterior = Builder.node ("a", {className: "BotonMes Anterior"}),
				this.textoMes = Builder.node ("span", {className: "TextoMes"}),
				this.botonMesSiguiente = Builder.node ("a", {className: "BotonMes Siguiente"})
			]),
			Builder.node ("table", [
				Builder.node ("tbody", [
					Builder.node ("tr", [
						Builder.node ("th", "Lun"),
						Builder.node ("th", "Mar"),
						Builder.node ("th", "Mie"),
						Builder.node ("th", "Jue"),
						Builder.node ("th", "Vie"),
						Builder.node ("th", "Sab"),
						Builder.node ("th", "Dom")
					]),
					filas
				])
			])
		]);
		document.body.appendChild (this.calendario);
		Event.observe (this.botonMesAnterior, "click", this.MesAnterior.bind(this));
		Event.observe (this.botonMesSiguiente, "click", this.MesSiguiente.bind(this));
	},
	
	MesAnterior: function ()
	{
		this.mesActual--;
		if (this.mesActual<0)
		{
			this.mesActual = 11;
			this.anoActual--;
		}
		this.ActualizarCalendario();
	},
	
	MesSiguiente: function ()
	{
		this.mesActual++;
		if (this.mesActual>11)
		{
			this.mesActual = 0;
			this.anoActual++;
		}
		this.ActualizarCalendario();
	},
	
	ClickCelda: function (i)
	{
		this.fecha = this.dias[i].fecha;
		this.ActualizarFecha();
		this.CerrarCalendario();
	},

	DesplegarCalendario: function ()
	{
		if (this.calendario==null) this.CrearCalendario();
		
		this.textoMes.innerHTML = this.meses[this.fecha.getMonth()] + " " + this.fecha.getFullYear();
		this.textoMes.style.width = (this.input.offsetWidth - 40) + "px";
		with (this.calendario)
		{
			Event.observe (document, "mousedown", this.ClickDocumento.bind(this));
			var posicion = this.input.cumulativeOffset();
			style.width = this.input.offsetWidth + "px";
			style.left = posicion.left + "px";
			style.top = (posicion.top + this.input.offsetHeight) + "px";
			this.mesActual = this.fecha.getMonth();
			this.anoActual = this.fecha.getFullYear();
			this.ActualizarCalendario();
			style.display = "block";
			focus();
		}	
	},

	CerrarCalendario: function ()
	{
		this.calendario.style.display = "none";
	},
	
	ClickDocumento: function (event)
	{
		var Donde = Event.element(event);
		if (Donde!=this.calendario && !Donde.descendantOf(this.calendario))
		{
			Event.stopObserving (document, "mousedown");
			this.CerrarCalendario();
		}		
	}
});

var CasillaCalendario = Class.create (
{
	hoy: null,
	fecha: null,
	celda: null,
	enlace: null,
	
	initialize: function ()
	{
		this.hoy = new Date();
		this.fecha = new Date();
		this.celda = Builder.node("td", [this.enlace=Builder.node("a")]);
		this.enlace.href = "javascript:;";
	},
	
	EstablecerFecha: function (fecha)
	{
		this.fecha = new Date(fecha.getFullYear(), fecha.getMonth(), fecha.getDate());
		this.enlace.innerHTML = this.fecha.getDate();
		this.enlace.title = this.fecha.toLocaleDateString();
		if (this.fecha.getDate()==this.hoy.getDate() && this.fecha.getMonth()==this.hoy.getMonth() && this.fecha.getFullYear()==this.hoy.getFullYear()) this.enlace.className = "Hoy";
		else this.enlace.className = "";
	},
	
	EstablecerClase: function (clase)
	{
		this.enlace.className = clase;
	}
});


var selectorPuntuacion = Class.create
({
 	capa: null,
	texto: null,
	marcador: null,
	seleccionado: null,
	imagenes: null,
	url: "",
	parametros: null,
	parametro: null,
	
	initialize: function (capa, texto, puntuacion, config)
	{
		this.capa = document.getElementById(capa);
		Element.addClassName (this.capa, "selectorPuntuacion");
		this.texto = Builder.node ("div", {className: "texto"}, texto);
		this.marcador = Builder.node ("div", {className: "marcador"});
		this.seleccionado = puntuacion+1;
		this.imagenes = new Array();
		this.url = config.url? config.url: "";
		this.parametros = config.parametros? config.parametros: {};
		this.parametro = config.parametro? config.parametro: "";

		var listado = Builder.node ("ul");
		var imagen;
		for (var i=0; i<=11; i++)
		{
			this.imagenes.push(Builder.node("a", {className: i==0? "vacio": "apagado", href: "javascript:;"}))
			imagen = Builder.node ("li", [this.imagenes[i]]);
			listado.appendChild (imagen);
			Event.observe (this.imagenes[i], "mouseover", this.encender.bind(this, i));
			Event.observe (this.imagenes[i], "click", this.enviarPuntuacion.bind(this, i));
		}
		this.capa.appendChild (this.texto);
		this.capa.appendChild (this.marcador);
		this.capa.appendChild (listado);

		this.encender (this.seleccionado);
		Event.observe (this.capa, "mouseout", this.restablecer.bind(this));
	},
	
	encender: function (i)
	{
		var a;
		for (a=1; a<=i; a++) this.imagenes[a].className = "encendido";
		for (a=i+1; a<this.imagenes.length; a++) this.imagenes[a].className = "apagado";
		if (i==0) this.marcador.innerHTML = "<span>--</span>";
		else this.marcador.innerHTML = "<span>" + (i-1) + "</span> /10";
 	},
	
	enviarPuntuacion: function (i)
	{
		this.seleccionado = i;
		this.parametros[this.parametro] = this.seleccionado==0? "": this.seleccionado-1;
		new Ajax.Request (this.url, {method: "post", parameters: this.parametros,
			onSuccess: function (transport)
			{
				var respuesta = transport.responseJSON;
				if (!respuesta.ok) dialogo.alert (respuesta.mensaje, {icono: "exclamacion.png"});
			},
			onFailure: function ()
			{
				dialogo.alert ("No se ha podido enviar la puntuación debido a un error", {icono: "error.png"});
			}
		});
	},
	
	restablecer: function ()
	{
		this.encender(this.seleccionado);
	}
});

var selectMultiple = Class.create (
{
	elemento: null,
	opciones: null,
	casillas: null,
	etiquetas: null,
	
	initialize: function (select)
	{
		this.opciones = new Array (select.options.length);
		this.casillas = new Array (select.options.length);
		this.etiquetas = new Array (select.options.length);
		for (var i=0; i<select.options.length; i++)
		{
			this.casillas[i] = Builder.node ("input", {type: "checkbox", name: select.name, value: select.options[i].value, id: select.name + "Opcion" + i});
			Event.observe (this.casillas[i], "click", this.casillaClick.bind (this, i));
			this.etiquetas[i] = Builder.node ("label", {htmlFor: select.name + "Opcion" + i}, select.options[i].innerHTML);
			this.opciones[i] = Builder.node ("li", {title: select.options[i].innerHTML}, [this.casillas[i], this.etiquetas[i]]);
			if (select.options[i].selected)
			{
				this.casillas[i].checked = true;
				Element.addClassName (this.opciones[i], "fondoPrimario");
				Element.addClassName (this.opciones[i], "colorSecundario");
			}
		}
		
		this.elemento = Builder.node ("div", {className: "selectMultiple", style: "width: " + select.offsetWidth + "px; height: " + select.offsetHeight + "px;"}, Builder.node ("ul", this.opciones));
		Element.insert (select, {after: this.elemento});
		Element.remove (select);
	},
	
	casillaClick: function (i)
	{
		if (this.casillas[i].checked)
		{
			Element.addClassName (this.opciones[i], "fondoPrimario");
			Element.addClassName (this.opciones[i], "colorSecundario");
		}
		else
		{
			Element.removeClassName (this.opciones[i], "fondoPrimario");
			Element.removeClassName (this.opciones[i], "colorSecundario");
		}
	}
});

var buscadorJuegos = Class.create (
{
	capa: null,
	texto: null,
	plataforma: "",
	enlacePlataformas: null,
	botonBuscar: null,
	listaPlataformas: null,
	
	initialize: function (capa)
	{
		this.capa = document.getElementById (capa);
		Element.addClassName (this.capa, "buscadorJuegos");
		var Yo = this;
		this.listaPlataformas = new listaSelect (this.capa.getElementsByTagName("select")[0], {actualizar: function(seleccionado){Yo.actualizarPlataforma(seleccionado);}});
		
		this.capa.appendChild (Builder.node ("div", {className: "i"}));
		this.capa.appendChild (Builder.node ("div", {className: "c"}, 
			[
				this.texto = Builder.node ("input", {className: "marcaAguaTexto", title: "Buscar juegos"}),
				this.enlacePlataformas = Builder.node ("a", {className: "plataforma"}, this.listaPlataformas.texto)
			]
		));
		this.botonBuscar =  Builder.node ("a", {className: "buscar", href: "javascript:;"});
		this.capa.appendChild (this.botonBuscar);
		
		Event.observe (this.texto, "keypress", this.teclaPulsada.bindAsEventListener (this));
		Event.observe (this.enlacePlataformas, "click", this.desplegarPlataformas.bind (this));
		Event.observe (this.botonBuscar, "click", this.buscar.bind (this));
	},
	
	desplegarPlataformas: function ()
	{
		var Posicion = Element.cumulativeOffset (this.enlacePlataformas);
		var PosicionBarra = Element.cumulativeOffset (this.capa);
		this.listaPlataformas.desplegar (Posicion.left - PosicionBarra.left, Posicion.top - PosicionBarra.top + this.enlacePlataformas.offsetHeight);
	},

	actualizarPlataforma: function (plataforma)
	{
		this.plataforma = this.listaPlataformas.valor;
		this.enlacePlataformas.innerHTML = this.listaPlataformas.texto;
	},
	
	teclaPulsada: function (event)
	{
		var tecla = (window.event) ? event.keyCode : event.which;
		if (tecla==13) this.buscar ();
	},
	
	buscar : function ()
	{
		var busqueda = "";
		if (this.texto.value != this.texto.title) busqueda += "&titulo=" + this.texto.value;
		if (this.plataforma != "") busqueda += "&plataforma=" + this.plataforma;
		
		if (busqueda.length > 0)
		{
			busqueda = busqueda.substring (1);
			window.location.href = "/juegos?" + busqueda;
		}
	}
});

var ventanaNotificacion = Class.create (
{
	ancho: 200,
	alto: 300,
	parametros: null,
	
	ventana: null,
	contenido: null,
	
	funcionDocumentClick: null,
	
	initialize: function (parametros)
	{
		this.parametros = parametros? parametros: {};
		this.ventana = Builder.node ("div", {className: "ventanaNotificacion", style: "display: none;"}, this.contenido = Builder.node ("div", {className: "contenido", style: "width: " + this.ancho + "px; height: " + this.alto + "px;"}));
		document.body.appendChild (this.ventana);
		this.generarContenido ();
	},
	
	generarContenido: function ()
	{
		
	},
	
	abrir: function (posX, posY)
	{
		this.ventana.style.left = posX;
		this.ventana.style.top = posY;
		this.ventana.style.display = "block";
		
		this.funcionDocumentClick = this.cerrarConClick.bindAsEventListener (this);
		Event.observe (document.body, "click", this.funcionDocumentClick);
		if (this.parametros.abierto) this.parametros.abierto ();
	},
	
	cerrar: function ()
	{
		this.ventana.style.display = "none";	
		if (this.parametros.cerrado) this.parametros.cerrado ();
	},
	
	cerrarConClick: function (event)
	{
		if (!Event.element(event).descendantOf (this.ventana))
		{
			Event.stopObserving (document.body, "click", this.funcionDocumentClick);
			this.funcionDocumentClick = null;
			this.cerrar ();
		}
	}
});

var enlaceInfo = Class.create (
{
	ancho: 500,
	alto: 250,
	retardo: 2000,
	url: "",

	enlace: null,
	ventana: null,
	contenido: null,
	sc: null,
	ic: null,
	ci: null,
	cd: null,
	derecha: false,
	abierta: false,
	cargado: false,
	procesado: false,
	datos: null,

	temporizador: null,
	ajax: null,	
	funcionDocumentClick: null,
	funcionCerrar: null,

	initialize: function (enlace)
	{
		this.enlace = enlace;
		this.url = this.generarURL ();
		Event.observe (this.enlace, "mouseover", this.iniciarTemporizador.bind (this));
		Event.observe (this.enlace, "mouseout", this.detenerTemporizador.bind (this));
	},
	
	generarURL: function ()
	{
		return "";
	},

	generarVentana: function ()
	{
		if (this.ventana == null)
		{
			Event.stopObserving (this.enlace, "mouseover");
			Event.stopObserving (this.enlace, "mouseout");

			var posicion = Element.cumulativeOffset (this.enlace);
			this.derecha = (posicion.left > document.body.offsetWidth / 2);
			var posX = this.derecha? (posicion.left + this.enlace.offsetWidth / 2) - this.ancho : (posicion.left + this.enlace.offsetWidth / 2) - 70;
			var posY = posicion.top - this.alto - 95;

			this.ventana = Builder.node ("div", {className: "ventanaEmergente", style: "width: " + (this.ancho+60) + "px; height: " + (this.alto+90) + "px; left: " + posX + "px; top: " + posY + "px; display: none;"},
				[
					Builder.node ("div", {className: "borde si"}),
					this.sc = Builder.node ("div", {className: "borde sc", style: "width: " + this.ancho + "px;"}),
					Builder.node ("div", {className: "borde sd"}),
					this.ci = Builder.node ("div", {className: "borde ci", style: "height: " + this.alto + "px;"}),
					this.contenido = Builder.node ("div", {className: "contenido", style: "width: " + this.ancho + "px; height: " + this.alto + "px;"}),
					this.cd = Builder.node ("div", {className: "borde cd", style: "height: " + this.alto + "px;"}),
					Builder.node ("div", {className: "borde ii"})
				]
			);

			if (this.derecha)
			{
				this.ic = this.ventana.appendChild (Builder.node ("div", {className: "borde ic largo", style: "width: " + (this.ancho-80) + "px;"}));
				this.ventana.appendChild (Builder.node ("div", {className: "borde fd"}));
				this.ventana.appendChild (Builder.node ("div", {className: "borde ic corto"}));
			}
			else
			{
				this.ventana.appendChild (Builder.node ("div", {className: "borde ic corto"}));
				this.ventana.appendChild (Builder.node ("div", {className: "borde fi"}));
				this.ic = this.ventana.appendChild (Builder.node ("div", {className: "borde ic largo", style: "width: " + (this.ancho-80) + "px;"}));
			}	
			this.ventana.appendChild (Builder.node ("div", {className: "borde id"}));

			document.body.appendChild (this.ventana);
			this.mostrar ();
			Event.observe (this.enlace, "mouseover", this.mostrar.bind (this));
		}
	},
	
	mostrar: function ()
	{
		if (!this.abierta)
		{
			this.abierta = true;
			this.ventana.style.display = "block";
			this.funcionDocumentClick = this.documentClick.bindAsEventListener (this);
			this.funcionCerrar = this.cerrar.bind (this);
			Event.fire (document, "ventanainfo:abierta");
			Event.observe (document, "click", this.funcionDocumentClick);
			Event.observe (document, "ventanainfo:abierta", this.funcionCerrar);
			if (!this.cargado) this.cargar ();
			else if (!this.procesado) this.datosRecibidos (this.datos);
		}
	},
	
	establecerAncho: function (nuevoAncho)
	{
		this.sc.style.width = nuevoAncho + "px";
		this.contenido.style.width= nuevoAncho + "px";
		this.ic.style.width = (nuevoAncho-80) + "px";
		this.ventana.style.width = (nuevoAncho + this.ci.offsetWidth + this.cd.offsetWidth) + "px";
		if (this.derecha) this.ventana.style.left = (parseInt (this.ventana.style.left) - (nuevoAncho - this.ancho)) + "px";
		this.ancho = nuevoAncho;
	},
	
	establecerAlto: function (nuevoAlto)
	{
		this.ci.style.height = nuevoAlto + "px";
		this.contenido.style.height = nuevoAlto + "px";
		this.cd.style.height = nuevoAlto + "px";
		this.ventana.style.top = (parseInt (this.ventana.style.top) - (nuevoAlto - this.alto)) + "px";
		this.alto = nuevoAlto;
	},
	
	cerrar: function ()
	{
		if (this.abierta)
		{
			Event.stopObserving (document, "click", this.funcionDocumentClick);
			Event.stopObserving (document, "ventanainfo:abierta", this.funcionCerrar);
			this.funcionDocumentClick = null;
			this.funcionCerrar = null;
			this.abierta = false;
			this.ventana.style.display = "none";
		}
	},
	
	documentClick: function (event)
	{
		if (!Event.element(event).descendantOf (this.contenido)) this.cerrar ();
	},
	
	cargar: function ()
	{
		if (this.ajax == null && !this.cargado)
		{
			Element.addClassName (this.contenido, "ajax");
			var Yo = this;
			this.ajax = new Ajax.Request (this.url, {
				onSuccess: function (transport)
				{
					Yo.datos = transport;
					if (Yo.abierta) Yo.datosRecibidos ();
				},
				onFailure: function ()
				{
					Yo.procesado = true;
					Yo.contenido.innerHTML = "Error cargando datos";
				},
				onComplete: function ()
				{
					Yo.cargado = true;
					Element.removeClassName (Yo.contenido, "ajax");
				}
			});
		}
	},
	
	datosRecibidos: function ()
	{
		this.procesado = true;
		this.procesarDatos ();
	},
	
	procesarDatos: function ()
	{
		this.contenido.innerHTML = "Ok";
	},

	iniciarTemporizador: function ()
	{
		this.temporizador = setTimeout (this.generarVentana.bind(this), this.retardo);
	},
	
	detenerTemporizador: function ()
	{
		if (this.temporizador != null)
		{
			clearTimeout (this.temporizador); 
			this.temporizador = null;
		}
	}
});

var enlaceJuego = Class.create (enlaceInfo,
{
	ancho: 300,
	alto: 150,
	
	generarURL: function ()
	{
		var idJuego = 0;
		var trozos = this.enlace.href.match (/(.+).viciojuegos.com\/juego\/(.+)\/(.+)\/([0-9]+)/i);
		if (trozos == null)
		{
			trozos = this.enlace.href.match (/(.+).viciojuegos.com\/juego.jsp?(.*)idJuego=([0-9]+)&?(.*)/i);
			if (trozos != null) idJuego = trozos[3];
		}
		else idJuego = trozos[4];
		return "/infoJuego.jsp?idJuego=" + idJuego;
	},
	
	procesarDatos: function ()
	{
		var juego = this.datos.responseText.evalJSON ();
		Element.addClassName (this.contenido, "fichaJuegoEmergente");

		if (juego.caratula != "")
		{
			var marcoCaratula = Builder.node ("div", {className: "izquierda"});
			this.contenido.appendChild (marcoCaratula);

			var yo = this;
			precargarImagen (juego.caratula, 
				function (url, ancho, alto)
				{
					yo.establecerAncho (yo.ancho + ancho + 10);
					marcoCaratula.appendChild (Builder.node ("img", {src: url, style: "margin-right: 10px;"}));
					if (datosJuego) datosJuego.style.marginLeft = (ancho + 10) + "px";
				}
			);
		}
		var datosJuego = Builder.node ("div", {style: "width: " + this.ancho + "px;"});
		if (juego.nota != "") datosJuego.appendChild (Builder.node ("a", {className: "marcadorPeque derecha", title: "Ver análisis de " + juego.titulo, href: "/todos-analisis/" + juego.tituloURL + "/" + juego.idJuego}, parseFloat(juego.nota)));
		datosJuego.appendChild (Builder.node ("h3", juego.titulo));
		datosJuego.appendChild (Builder.node ("span", {className: "marco", style: "color: " + juego.colorPlataforma + ";"}, juego.plataforma));
		
		if (juego.desarrolladoras.length > 0) datosJuego.appendChild (Builder.node ("p", [Builder.node ("strong", "Desarrolladora" + (juego.desarrolladoras.length>1?"s":"")), Builder.node ("span", juego.desarrolladoras.join (", "))]));
		if (juego.productoras.length > 0) datosJuego.appendChild (Builder.node ("p", [Builder.node ("strong", "Productora" + (juego.productoras.length>1?"s":"")), Builder.node ("span", juego.productoras.join (", "))]));
		if (juego.distribuidoras.length > 0) datosJuego.appendChild (Builder.node ("p", [Builder.node ("strong", "Distribuidora" + (juego.distribuidoras.length>1?"s":"")), Builder.node ("span", juego.distribuidoras.join (", "))]));
		
		if (juego.usuariosCatalogo > 0) datosJuego.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioCatalogo", href: "/usuariosJuego.jsp?comprado=true&idJuego=" + juego.idJuego, title: juego.usuariosCatalogo + " usuario" + (juego.usuariosCatalogo!=1?"s":"") + " poseen " + juego.titulo}, juego.usuariosCatalogo));
		if (juego.usuariosDeseos > 0) datosJuego.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioDeseos", href: "/usuariosJuego.jsp?comprado=false&idJuego=" + juego.idJuego, title: juego.usuariosDeseos + " usuario" + (juego.usuariosDeseos!=1?"s":"") + " tienen " + juego.titulo + " en su lista de deseos"}, juego.usuariosDeseos));
		if (juego.usuariosFavoritos > 0) datosJuego.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioFavoritos", href: "/usuariosJuego.jsp?favorito=true&idJuego=" + juego.idJuego, title: juego.usuariosFavoritos + " usuario" + (juego.usuariosFavoritos!=1?"s":"") + " tienen " + juego.titulo + " en su lista de juegos favoritos"}, juego.usuariosFavoritos));
		if (juego.usuariosVenta > 0) datosJuego.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioVenta", href: "/usuariosJuego.jsp?enVenta=true&idJuego=" + juego.idJuego, title: juego.usuariosVenta + " usuario" + (juego.usuariosVenta!=1?"s":"") + " quieren vender " + juego.titulo + " en el mercadillo"}, juego.usuariosVenta));
		if (juego.usuariosCompra > 0) datosJuego.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioCompra", href: "/usuariosJuego.jsp?compro=true&idJuego=" + juego.idJuego, title: juego.usuariosCompra + " usuario" + (juego.usuariosCompra!=1?"s":"") + " quieren comprar " + juego.titulo + " en el mercadillo"}, juego.usuariosCompra));
		
		this.contenido.appendChild (datosJuego);
	}
});	

var enlaceUsuario = Class.create (enlaceInfo,
{
	ancho: 400,
	alto: 150,
	marcoAvatar: null,
	
	generarURL: function ()
	{
		var nick = "";
		var trozos = this.enlace.href.match (/(.+).viciojuegos.com\/fichaUsuario.jsp?(.*)nick=(.+)&?(.*)/i);
		if (trozos != null) nick = trozos[3];
		return "/infoUsuario.jsp?nick=" + nick;
	},
	
	procesarDatos: function ()
	{
		var usuario = this.datos.responseText.evalJSON ();
		var textoBocadillo = null;
		
		Element.addClassName (this.contenido, "fichaUsuarioEmergente");
		if (usuario.ultimoMensaje.length > 0)
		{
			var bocadillo = Builder.node ("div", {className: "ultimoMensaje"},
				[
					Builder.node ("div", {className: "borde si"}),
					Builder.node ("div", {className: "sc", style: "width: " + (this.ancho-10) + "px"}),
					Builder.node ("div", {className: "borde sd"}),
					textoBocadillo = Builder.node ("p", {style: "width: " + (this.ancho-12) + "px"}, usuario.ultimoMensaje),
					Builder.node ("div", {className: "borde ii"}),
					Builder.node ("div", {className: "ic", style: "width: " + (this.ancho-110) + "px"}),
					Builder.node ("div", {className: "borde id"})
				]
			);
			this.contenido.appendChild (bocadillo);
			bocadillo.style.height = textoBocadillo.offsetHeight + 18;
			this.establecerAlto (this.alto + textoBocadillo.offsetHeight + 25);
		}
		
		if (usuario.avatar.length > 0)
		{
			usuario.avatar = "http://www.viciojuegos.com" + usuario.avatar;
			this.marcoAvatar = Builder.node ("div", {className: "izquierda"});
			this.contenido.appendChild (this.marcoAvatar);
			
			var yo = this;
			precargarImagen (usuario.avatar,
				function (url, ancho, alto)
				{
					yo.marcoAvatar.appendChild (Builder.node ("img", {src: url, className: "avatar"}));
				}
			);
		}
		
		var datosUsuario = Builder.node ("div", {className: "izquierda", style: "width: " + (usuario.avatar == ""? this.ancho: (this.ancho - 90)) + "px;"});
		var nick = Builder.node ("h3", usuario.nick);
		if (usuario.esAdmin) nick.appendChild (Builder.node ("img", {src: rutaImagenes + "web/mod.png"}));
		datosUsuario.appendChild (nick);
		if (usuario.rangoVisible) datosUsuario.appendChild (Builder.node ("span", {className: "marco"}, usuario.vjs + " VJ's - " + usuario.rango));
		if (usuario.nombreReal.length > 0) datosUsuario.appendChild (Builder.node ("p", [Builder.node ("strong", "Nombre real"), Builder.node ("span", usuario.nombreReal)]));
		datosUsuario.appendChild (Builder.node ("p", [Builder.node ("strong", "Registrado el"), Builder.node ("span", usuario.fechaAlta)]));
		//if (usuario.poblacion.length > 0) datosUsuario.appendChild (Builder.node ("p", [Builder.node ("strong", "Reside en"), Builder.node ("span", usuario.poblacion)]));
		//if (usuario.edad != 0) datosUsuario.appendChild (Builder.node ("p", [Builder.node ("strong", "Edad"), Builder.node ("span", usuario.edad + " años")]));
		
		var social = Builder.node ("p", Builder.node ("strong", "Síguele en"));
		if (usuario.facebook.length > 0) social.appendChild (Builder.node ("a", {href: usuario.facebook, target: "_blank", title: "Sigue a " + usuario.nick + " en Facebook"}, Builder.node ("img", {src: rutaImagenes + "web/social_facebook.png"})));
		if (usuario.twitter.length > 0) social.appendChild (Builder.node ("a", {href: usuario.twitter, target: "_blank", title: "Sigue a " + usuario.nick + " en Twitter"}, Builder.node ("img", {src: rutaImagenes + "web/social_twitter.png"})));
		if (usuario.tuenti.length > 0) social.appendChild (Builder.node ("a", {href: usuario.tuenti, target: "_blank", title: "Sigue a " + usuario.nick + " en Tuenti"}, Builder.node ("img", {src: rutaImagenes + "web/social_tuenti.png"})));
		if (usuario.youtube.length > 0) social.appendChild (Builder.node ("a", {href: usuario.youtube, target: "_blank", title: "Sigue a " + usuario.nick + " en Youtube"}, Builder.node ("img", {src: rutaImagenes + "web/social_youtube.png"})));
		if (usuario.flickr.length > 0) social.appendChild (Builder.node ("a", {href: usuario.flickr, target: "_blank", title: "Sigue a " + usuario.nick + " en Flickr"}, Builder.node ("img", {src: rutaImagenes + "web/social_flickr.png"})));
		if (usuario.lastfm.length > 0) social.appendChild (Builder.node ("a", {href: usuario.lastfm, target: "_blank", title: "Sigue a " + usuario.nick + " en Last.fm"}, Builder.node ("img", {src: rutaImagenes + "web/social_lastfm.png"})));
		if (social.getElementsByTagName ("a").length > 0) datosUsuario.appendChild (social);

		datosUsuario.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioCatalogo", href: "/juegosUsuario.jsp?comprado=true&nick=" + usuario.nick, title: usuario.nick + " tiene " + usuario.juegosCatalogo + " juego" + (usuario.juegosCatalogo!=1?"s":"") + " en su catálogo personal"}, usuario.juegosCatalogo.toString()));
		datosUsuario.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioDeseos", href: "/juegosUsuario.jsp?comprado=false&nick=" + usuario.nick, title: usuario.nick + " tiene " + usuario.juegosDeseos + " juego" + (usuario.juegosDeseos!=1?"s":"") + " en su lista de deseos"}, usuario.juegosDeseos.toString()));
		datosUsuario.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioFavoritos", href: "/juegosUsuario.jsp?favorito=true&nick=" + usuario.nick, title: usuario.nick + " tiene " + usuario.juegosFavoritos + " juego" + (usuario.juegosFavoritos!=1?"s":"") + " en su lista de favoritos"}, usuario.juegosFavoritos.toString()));
		if (usuario.juegosVenta > 0) datosUsuario.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioVenta", href: "/juegosUsuario.jsp?enVenta=true&nick=" + usuario.nick, title: usuario.nick + " tiene " + usuario.juegosVenta + " juego" + (usuario.juegosVenta!=1?"s":"") + " en venta en el mercadillo"}, usuario.juegosVenta.toString()));
		if (usuario.juegosCompra > 0) datosUsuario.appendChild (Builder.node ("a", {className: "enlaceUsuarios usuarioCompra", href: "/juegosUsuario.jsp?compro=true&nick=" + usuario.nick, title: usuario.nick + " quiere comprar " + usuario.juegosCompra + " juego" + (usuario.juegosCompra!=1?"s":"") + " en el mercadillo"}, usuario.juegosCompra.toString()));
			
		this.contenido.appendChild (datosUsuario);
	}
});


var encuesta = Class.create
({
	capa: null,
	divFormulario: null,
	formulario: null,
	idEncuesta: null,
	botonEnviar: null,
	
	initialize: function (capa)
	{
		this.capa = document.getElementById (capa);
		this.divFormulario = Element.select (this.capa, ".formularioEncuesta")[0];
		this.formulario = this.capa.getElementsByTagName ("form")[0];
		this.idEncuesta = this.formulario.idEncuesta.value;
		this.botonEnviar = Element.select (this.capa, ".botonEnviar")[0];	
		Event.observe (this.botonEnviar, "click", this.enviarFormulario.bind (this));
	},
	
	enviarFormulario: function ()
	{
		this.divFormulario.style.display = "none";
		Element.addClassName (this.capa, "animAjax");
		
		var yo = this;
		new Form.request (this.formulario, {
			onSuccess: function (transport)
			{
				yo.enviadoOk (transport);
			},
			onFailure: function (transport)
			{
				yo.divFormulario.style.display = "block";
				dialogo.alert ("No se ha podido enviar tu respuesta debido a un error. Vuelve a intentarlo en otro instante.", {icono: "error.png"});
			},
			onComplete: function ()
			{
				Element.removeClassName (yo.capa, "animAjax");
			}		
		});
	},
	
	enviadoOk: function (transport)
	{
		var respuesta = transport.responseText.evalJSON ();
		
		if (respuesta.ok)
		{
			var yo = this;
			new Ajax.Request ("/encuestaJSON.jsp?idEncuesta=" + this.idEncuesta, {onSuccess: function (transport){yo.mostrarResultados(transport);}});
		}
		else
		{
			this.divFormulario.style.display = "block";
			dialogo.alert (respuesta.mensaje, {icono: "exclamacion.png"});
		}
	},
	
	mostrarResultados: function (transport)
	{
		var respuesta = transport.responseText.evalJSON ();

		var preguntas = respuesta.preguntas;
		var colores = ["pink", "red", "blue", "green", "gray", "orange", "yellow", "purple"];
		var i = 0;
		var j = 0;
		var resultados = Builder.node ("div", {className: "resultadosEncuesta"});
		this.capa.appendChild (resultados);
		
		for (i=0; i<preguntas.length; i++)
		{
			resultados.appendChild (Builder.node ("p", {className: "textoPregunta"}, preguntas[i].pregunta));
			if (preguntas[i].descripcion.length > 0) resultados.appendChild (Builder.node ("p", {className: "textoPeque"}, preguntas[i].descripcion));
			resultados.appendChild (Builder.node ("p", Builder.node("strong", "Resultados provisionales")));
			
			for (j=0; j<preguntas[i].respuestas.length; j++)
			{
				preguntas[i].respuestas[j].porcentaje = preguntas[i].respuestas[j].porcentaje.replace (",", ".");
				resultados.appendChild (Builder.node ("p", {className: "textoPeque"}, preguntas[i].respuestas[j].respuesta));
				resultados.appendChild (Builder.node ("div", {className: "respuesta"},
					[
						Builder.node ("div", {className: "porcentaje"}, preguntas[i].respuestas[j].porcentaje + "%"),
						Builder.node ("div", {className: "barra"}, Builder.node ("div", {className: "degradado", style: "background-color: " + colores[j%8] + "; width: " + preguntas[i].respuestas[j].porcentaje + "%;"}))
					])
				);
			}
		}
	}
});

var respuestasAportacion = Class.create (
{
	ancho: 830,

	idAportacion: 0,
	capaPosicion: null,
	enlace: null, // Variable que almacena el enlace que vamos a capturar.
	
	
	ventana: null,
	contenido: null,
	sc: null,
	ic: null,
	ci: null,
	cd: null,
	derecha: false,
	abierta: false,
	cargado: false,
	procesado: false,
	datos: null,

	ajax: null,	

	initialize: function (idAportacion, capaComentarios, pagina)
	{
		this.idAportacion = idAportacion;
		this.capaComentarios = capaComentarios;
		this.pagina = pagina;
		
		this.capaComentarios.innerHTML = '<img src="/img/web/ajax.gif">';
	},
	
	// Función que se ejecuta cuando el usuario hace click en el enlace
	leerComentarios: function ()
	{
		// Declarar esta variable es necesario, ya que la variable this no funciona dentro del onSuccess.
		var yo = this;
		
		// Hacemos la llamada ajax a comentariosAportacion.jsp (no sé si el archivo se llama así, cámbialo por el que corresponda)
		/*new Ajax.Request ("/respuestasJSON.jsp?idAportacion=" + this.idAportacion + "&paginaAportacion=" + this.pagina, {
			onSuccess: function (transport)
			{
				// onSuccess se ejecuta si la petición tiene éxito. Transport contiene información sobre la petición.
				yo.procesarDatos (transport);
				
			},
			onFailure: function ()
			{
				// onFailure se ejecuta si la petición falla (error 500, por ejemplo)
				yo.capaComentarios.appendChild (Builder.node ("p", "Error en la petición de los datos. Algo así como 'El Apache Ataca'. Avisa a <a href=\"/fichaUsuario.jsp?nick=CodeRed\">CodeRed</a> de este problema por favor."));
				
			},
			onComplete: function ()
			{
				// onComplete se ejecuta cuando la petición termina, da igual si con éxito o con error.
			}
		});*/
		new Ajax.Updater (this.capaComentarios, "/respuestas.jsp?idAportacion=" + this.idAportacion + "&paginaAportacion=" + this.pagina);
		
		// return false es necesario para cancelar la acción por defecto del enlace, que sería irse al foro
		return false;
	},
	
	
	// Esta función es la que debería dibujar las respuestas
	procesarDatos: function (transport)
	{
		
		try {
			var respuestasAportacion = transport.responseText.evalJSON ();
		} catch (E) {
			this.capaComentarios.appendChild (Builder.node ("p", "Cadena JSON formada incorrectamente. Avisa a <a href=\"/fichaUsuario.jsp?nick=CodeRed\">CodeRed</a> de este problema por favor."));
		}
		
		var htmlComentarios = '';
		
		if (respuestasAportacion.paginaAnterior>0 || respuestasAportacion.paginaSiguiente>0) {
			htmlComentarios += '<table width="100%">';
			htmlComentarios += '	<tr>';
			htmlComentarios += '		<td width="50%" align="left">';
			if (respuestasAportacion.paginaAnterior>0) {
				htmlComentarios += '		<input type="button" onClick="cargarComentarios(' + respuestasAportacion.paginaAnterior + ')" class="formularioBoton" value="M&Aacute;S ANTIGUOS">';
			}
			htmlComentarios += '		</td>';
			htmlComentarios += '		<td width="50%" align="right">';
			if (respuestasAportacion.paginaSiguiente>0) {
				htmlComentarios += '		<input type="button" onClick="cargarComentarios(' + respuestasAportacion.paginaSiguiente + ')" class="formularioBoton" value="M&Aacute;S NUEVOS">';
			}
			htmlComentarios += '		</td>';
			htmlComentarios += '	</tr>';
			htmlComentarios += '</table>';
		}
		
		for (var i=0; i < respuestasAportacion.respuestas.length; i++) {
			
			var comentario = respuestasAportacion.respuestas[i];

			htmlComentarios += '<div class="comentariosContenidos">';

			htmlComentarios += '<div style="height:50px;border:1px dotted gray; width:810px; ';

			if (comentario.borrada!=0)
				htmlComentarios += 'background-color:#ffeeee';
			else
				htmlComentarios += 'background-color:#f6f6f6';
				
			htmlComentarios += '; padding:5px; margin-bottom:5px" id="comentario' + comentario.idAportacion + '">';
			
			htmlComentarios += comentario.titulo;
			
			var avatar = comentario.avatar;
			if (avatar.length>0)
			{
				avatar = "http://www.viciojuegos.com" + avatar;
				
				htmlComentarios += '<img src="' + avatar + '" class="avatar" align="left" width="50" height="50" style="margin-right:5px">';
			}
			
			htmlComentarios += '<br><i>' + comentario.fecha + '</i>';

			htmlComentarios += '<br>';			

			var usuario = '';
			if (comentario.nombreCompleto.length > 0)
				usuario = comentario.nombreCompleto;
			else
				usuario = comentario.usuario;

			htmlComentarios += '<a href="/fichaUsuario.jsp?nick=' + comentario.usuario + '">' + comentario.usuario + '</a>';

			if (respuestasAportacion.esAdmin) {
				htmlComentarios += '<div class="opcionesAdministracion derecha">';
				var recuperarDisplay='none';
				var borrarDisplay='block';
				if (comentario.borrada) {
					recuperarDisplay = 'block';
					borrarDisplay = 'none';
				} else {
					recuperarDisplay = 'none';
					borrarDisplay = 'block';
				}
				htmlComentarios += '	<div id="recuperarComentario' + comentario.idAportacion + '" style="display:' + recuperarDisplay + '"><a href="/recuperarAportacion.jsp?idAportacion=' + comentario.idAportacion + '" onClick="document.getElementById(\'comentario' + comentario.idAportacion+ '\').style.backgroundColor=\'#f6f6f6\';document.getElementById(\'recuperarComentario' + comentario.idAportacion + '\').style.display=\'none\';document.getElementById(\'borrarComentario' + comentario.idAportacion + '\').style.display=\'block\';"  target="destino">R</a></div>';
				htmlComentarios += '	<div id="borrarComentario' + comentario.idAportacion + '" style="display:' + borrarDisplay + '"><a href="/borrarAportacion.jsp?idAportacion=' + comentario.idAportacion + '" onClick="document.getElementById(\'comentario' + comentario.idAportacion+ '\').style.backgroundColor=\'#ffeeee\';document.getElementById(\'recuperarComentario' + comentario.idAportacion + '\').style.display=\'block\';document.getElementById(\'borrarComentario' + comentario.idAportacion + '\').style.display=\'none\';"  target="destino">B</a></div>';
				htmlComentarios += '</div>';
			}

			if (respuestasAportacion.esAdmin || comentario.usuario==respuestasAportacion.usuario) {
				htmlComentarios += '<div class="opcionesAdministracion derecha">';
				htmlComentarios += ' <a href="/editarAportacion.jsp?idAportacion=' + comentario.idAportacion + '">EDITAR</a>';
				htmlComentarios += '</div>';
			}
				
			htmlComentarios += '</div>';
			
			var texto = comentario.texto;
			
			while (texto.indexOf('\n')>=0)
				texto = texto.replace('\n','\\n');

			while (texto.indexOf('<')>=0)
				texto = texto.replace('<','&lt;');

			while (texto.indexOf('>')>=0)
				texto = texto.replace('>','&gt;');

			while (texto.indexOf('"')>=0)
				texto = texto.replace('"','&quot;');
			
			htmlComentarios += '<div style="border:1px dotted gray; width:810px; background-color:#f9f9f9;padding:5px">';
			
			htmlComentarios += comentario.texto;
			
			htmlComentarios += '<div style="text-align:right;margin:5px">';
			if (respuestasAportacion.estaConectado) {
				htmlComentarios += '<input type="button" onClick="colocarTexto(\'' + texto + '\',\'' + comentario.titulo + '\',\'' + comentario.usuario + '\',' + comentario.idAportacion + ');" value="RESPONDER A ' + comentario.usuario + ' >>" class="formularioBoton"><br>';
			} else
				htmlComentarios += '<br><a href="/registro.jsp">Regístrate</a> o <a href="javascript:enfocarLogin();">inicia sesión</a> para responder a esta aportación.<br>';
			htmlComentarios += '</div>';
			
			htmlComentarios += '</div>';
			
			htmlComentarios += '</div>';
		}

		if (respuestasAportacion.paginaAnterior>0 || respuestasAportacion.paginaSiguiente>0) {
			htmlComentarios += '<table width="100%">';
			htmlComentarios += '	<tr>';
			htmlComentarios += '		<td width="50%" align="left">';
			if (respuestasAportacion.paginaAnterior>0) {
				htmlComentarios += '		<input type="button" onClick="cargarComentarios(' + respuestasAportacion.paginaAnterior + ')" class="formularioBoton" value="M&Aacute;S ANTIGUOS">';
			}
			htmlComentarios += '		</td>';
			htmlComentarios += '		<td width="50%" align="right">';
			if (respuestasAportacion.paginaSiguiente>0) {
				htmlComentarios += '		<input type="button" onClick="cargarComentarios(' + respuestasAportacion.paginaSiguiente + ')" class="formularioBoton" value="M&Aacute;S NUEVOS">';
			}
			htmlComentarios += '		</td>';
			htmlComentarios += '	</tr>';
			htmlComentarios += '</table>';
		}

		this.capaComentarios.innerHTML = htmlComentarios;
	}

});

var lightbox = 
{
	maxAncho: 0,
	maxAlto: 0,
	lightbox: null,
	contenido: null,
	espacioInferior: null,
	titulo: null,
	botonCerrar: null,
	
	funcionCentrar: null,
	funcionTeclaPulsada: null,
	funcionCerrado: null,
	
	generar: function ()
	{
		if (this.lightbox == null)
		{
			var tamano = document.viewport.getDimensions ();
			this.maxAncho = tamano.width - 120;
			this.maxAlto = tamano.height - 150;
			
			this.lightbox = Builder.node ("div", {className: "lightbox", style : "display: none;"},
			[
				this.contenido = Builder.node ("div", {className: "contenido"}),
				this.espacioInferior = Builder.node ("div", {className: "espacioInferior"},
				[
					this.titulo = Builder.node ("p", {className: "titulo izquierda"}),
					this.botonCerrar = Builder.node ("a", {className: "botonTuneado derecha", href: "javascript:;"}, "Cerrar")
				])
			]);
			tunearEnlace (this.botonCerrar);
			Event.observe (this.botonCerrar, "click", function () {fondoDialogo.cerrar ();});
			document.body.appendChild (this.lightbox);
		}
	},
	
	abrir: function (cerrado)
	{
		fondoDialogo.abrir (true, this.cerrar.bind (this));
		this.lightbox.style.display = "block";
		this.centrar ();
		
		this.funcionCentrar = this.centrar.bind (this);
		this.funcionTeclaPulsada = this.teclaPulsada.bindAsEventListener (this);
		if (cerrado != null) this.funcionCerrado = cerrado;
		Event.observe (window, "resize", this.funcionCentrar);
		Event.observe (window, "scroll", this.funcionCentrar);
		Event.observe (document, "keyup", this.funcionTeclaPulsada);
	},
	
	cerrar: function ()
	{
		Event.stopObserving (window, "resize", this.funcionCentrar);
		Event.stopObserving (window, "scroll", this.funcionCentrar);
		Event.stopObserving (document, "keyup", this.funcionTeclaPulsada);
		
		if (this.funcionCerrado != null) this.funcionCerrado ();
		if (this.funcionTeclaPulsada != null) this.funcionTeclaPulsada = null;
		this.lightbox.style.display = "none";
		
		var elementos = Element.childElements (this.contenido);
		for (var i = elementos.length - 1; i >= 0; i--) Element.remove (elementos[i]);
		this.titulo.innerHTML = "";
		this.contenido.innerHTML = "";
	},
	
	centrar: function ()
	{
		var posicion = document.viewport.getScrollOffsets ();
		var tamano = document.viewport.getDimensions ();
		
		with (this.lightbox.style)
		{
			left = ((tamano.width - this.lightbox.offsetWidth) / 2) + "px";
			top = (posicion.top + ((tamano.height - this.lightbox.offsetHeight) / 2)) + "px";
		}
	},
	
	teclaPulsada: function (event)
	{
		var tecla = (window.event) ? event.keyCode : event.which;
		if (tecla == 27) fondoDialogo.cerrar ();
	}
};

var lightboxBase = Class.create
({
	enlace: null,

	initialize: function (enlace)
	{
		this.enlace = enlace;
		this.enlace.onclick = this.abrir.bind (this);
	},

	abrir: function ()
	{
		this.construir ();
		if (this.enlace.title != undefined) lightbox.titulo.innerHTML = this.enlace.title;
		lightbox.abrir (this.cerrado.bind (this));
		return false;
	},

	construir: function ()
	{
		this.contenido.appendChild (Builder.node ("p", "La clase lightboxBase no se puede utilizar directamente."));		
	},

	cerrado: function ()
	{
		// Esta función es solo para heredarla. Aquí no se pone nada directamente.
	}
});

var lightboxVideo = Class.create (lightboxBase,
{
	iframe: null,
	infoVideo: null,
	
	construir: function ()
	{
		this.infoVideo = obtenerVideoEmbed (this.enlace.href);
		
		var capaVideo = Builder.node ("div", {style: "width: " + lightbox.maxAncho + "px; height: " + lightbox.maxAlto + "px;"});
		if (this.infoVideo.flash)
		{
			capaVideo.appendChild (Builder.node ("div", {id: "lightboxVideo"}, Builder.node ("p", {className: "textoCentrado", style: "line-height: " + lightbox.maxAlto + "px"}, "Necesitas el plug-in Adobe Flash Player para poder ver este vídeo.")));
			swfobject.embedSWF (this.infoVideo.url, "lightboxVideo", lightbox.maxAncho, lightbox.maxAlto, "10.0", null, null, null, {id: "reproductorLightboxVideo"});
		}
		else
		{
			this.iframe = Builder.node ("iframe", {src: this.infoVideo.url, frameborder: "0", scrolling: "no", style: "width: " + lightbox.maxAncho + "px; height: " + lightbox.maxAlto + "px;"});
			capaVideo.appendChild (this.iframe);
		}
		lightbox.contenido.appendChild (capaVideo);
	},

	cerrado: function ()
	{
		if (this.infoVideo.flash) swfobject.removeSWF ("lightboxVideo");
		else this.iframe.remove ();
	}
});

var lightboxImagen = Class.create (lightboxBase,
{
	capaCargando: null,
	capaContenido: null,
	capaError: null,
	barraTamano: null,
	imagen: null,
	
	construir: function ()
	{
		this.capaCargando = Builder.node ("div", {className: "cargando"}, Builder.node ("p", {className: "textoCentrado"}, "Cargando imagen"));
		lightbox.contenido.appendChild (this.capaCargando);
		
		var yo = this;
		precargarImagen (this.enlace.href, function (url, ancho, alto) {yo.imagenCargada (url, ancho, alto);}, function (url) {yo.imagenError (url);});
	},
	
	imagenCargada: function (url, ancho, alto)
	{
		var nuevoAncho = ancho;
		var nuevoAlto = alto;
		
		if (nuevoAncho > lightbox.maxAncho)
		{
			var relacion = nuevoAlto / nuevoAncho;
			nuevoAncho = lightbox.maxAncho;
			nuevoAlto = Math.round (nuevoAncho * relacion);
		}
		if (nuevoAlto > (lightbox.maxAlto-15))
		{
			var relacion = nuevoAncho / nuevoAlto;
			nuevoAlto = lightbox.maxAlto - 15;
			nuevoAncho = Math.round (nuevoAlto * relacion);
		}
		
		
		if (ancho != nuevoAncho || alto != nuevoAlto)
		{
			this.barraTamano = Builder.node ("a", {href: this.enlace.href, target: "_blank", className: "barraTamano"}, "Esta imagen está redimensionada para que encaje en tu monitor. Pulsa aquí para verla a su tamaño original (" + ancho + "x" + alto + ").");
			lightbox.contenido.appendChild (this.barraTamano);
		}
		this.capaCargando.style.display = "none";
		this.imagen = Builder.node ("img", {src: url, className: "imagenAmpliada", style: "width: " + nuevoAncho + "px; height: " + nuevoAlto + "px"});
		lightbox.contenido.appendChild (this.imagen);
		Event.observe (this.imagen, "click", function() {fondoDialogo.cerrar();});
		
		lightbox.centrar ();
	},
	
	imagenError: function (url)
	{
		this.capaError = Builder.node ("p", {className: "textoCentrado"}, "No se ha podido cargar la imagen");
		lightbox.contenido.appendChild (this.capaError);
		this.capaCargando.style.display = "none";
	},

	cerrado: function ()
	{
		Element.remove (this.capaCargando);
		this.capaCargando = null;
		if (this.capaError != null)
		{
			Element.remove (this.capaError);
			this.capaError = null;
		}
		if (this.barraTamano != null)
		{
			Element.remove (this.barraTamano);
			this.barraTamano = null;
		}
		if (this.imagen != null)
		{
			Event.stopObserving (this.imagen);
			Element.remove (this.imagen);
			this.imagen = null;
		}
	}
});

var ventanaNotificaciones =
{
	notificaciones: null,
	botonNotificaciones: null,
	numNotificaciones: null,
	noLeidas: 0,
	ultimoId: 0,
	tituloPagina: "",
	
	generada: false,
	ventana: null,
	cargando: null,
	error: null,
	lista: null,
	abierta: false,
	listaNotificaciones: null,
	ancho: 280,

	intervaloActualizacion: 10000,
	temporizador: null,

	funcionDescargar: null,
	funcionDescargarOk: null,
	funcionDescargarError: null,
	funcionDescargaFinalizada: null,
	funcionDocumentClick: null,

	inicializar: function (botonNotificaciones)
	{
		this.botonNotificaciones = $(botonNotificaciones);
		if (this.botonNotificaciones != null)
		{
			this.notificaciones = new Array ();
			this.numNotificaciones = this.botonNotificaciones.down (".numeroMensajes");
			var titulo = document.title.match (/^\(([0-9]+)\) (.+)$/);
			this.tituloPagina = titulo == null? document.title: titulo[2];

			this.funcionDescargar = this.descargarNotificaciones.bind (this);
			this.funcionDescargarOk = this.descargarOk.bind (this);
			this.funcionDescargarError = this.descargarError.bind (this);
			this.funcionDescargaFinalizada = this.descargaFinalizada.bind (this);
			this.funcionDocumentClick = this.documentClick.bindAsEventListener (this);

			this.botonNotificaciones.observe ("click", this.abrir.bind (this));
			this.iniciarTemporizador ();
		}
	},

	abrir: function ()
	{
		if (this.abierta) this.cerrar ();
		else
		{
			Element.addClassName (this.botonNotificaciones, "seleccionado");
			if (!this.generada) this.generar ();

			var posicion = Element.cumulativeOffset (this.botonNotificaciones);
			this.ventana.style.left = posicion.left + "px";
			this.ventana.style.top = (posicion.top + this.botonNotificaciones.offsetHeight) + "px";
			this.ventana.removeClassName ("ocultar");

			Event.observe (document.body, "mousedown", this.funcionDocumentClick);
			this.abierta = true;
			if (this.notificaciones.length == 0) this.descargarNotificaciones ();
			if (this.listaNotificaciones.length == 0) this.generarListado ();
		}
	},

	cerrar: function ()
	{
		if (this.abierta)
		{
			this.ventana.addClassName ("ocultar");
			Element.removeClassName (this.botonNotificaciones, "seleccionado");
			Event.stopObserving (document.body, "mousedown", this.funcionDocumentClick);
			this.abierta = false;
		}
	},

	documentClick: function (event)
	{
		var elemento = Event.element (event);
		if (!elemento.descendantOf (this.ventana) && elemento != this.ventana && !elemento.descendantOf (this.botonNotificaciones) && elemento != this.botonNotificaciones) this.cerrar ();
	},

	generar: function ()
	{
		var enlaceReintentar;
		this.cargando = Builder.node ("div", {className: "cargando ocultar"}, "Cargando...");
		this.error = Builder.node ("div", {className: "error ocultar"},
		[
			Builder.node ("p", {className: "textoCentrado"}, "Se ha producido un error."),
			enlaceReintentar = Builder.node ("a", "Reintentar")
		]);
		this.lista = Builder.node ("ul", {className: "ocultar"});
		this.ventana = Builder.node ("div", {className: "ventanaNotificaciones ocultar", style: "width: " + this.ancho + "px;"},
		[
			this.cargando,
			this.error,
			this.lista
		]);
		this.listaNotificaciones = new Array ();
		document.body.appendChild (this.ventana);
		enlaceReintentar.observe ("click", this.funcionDescargar);
		this.generada = true;
	},

	generarListado: function ()
	{
		var i = 0;
		for (i = 0; i < this.listaNotificaciones.length; i++)
		{
			this.listaNotificaciones[i].quitar ();
			this.listaNotificaciones[i] = null;
		}
		this.listaNotificaciones = new Array (this.notificaciones.length);
		
		for (i = 0; i < this.notificaciones.length; i++)
		{
			this.listaNotificaciones[i] = new notificacion (this, this.notificaciones[i]);
			this.listaNotificaciones[i].elemento.addClassName (i % 2 == 0? "par": "impar");
		}
		this.lista.removeClassName ("ocultar");
	},

	descargarNotificaciones: function ()
	{
		this.detenerTemporizador ();
		if (this.generada)
		{
			this.lista.addClassName ("ocultar");
			this.error.addClassName ("ocultar");
			this.cargando.removeClassName ("ocultar");
		}
		new Ajax.Request ("/notificacionesUsuarioJSON.jsp", {method: "post",
			onSuccess: this.funcionDescargarOk,
			onFailure: this.funcionDescargarError,
			onComplete: this.funcionDescargaFinalizada
		});
	},

	descargarOk: function (transport)
	{
		var respuesta = transport.responseJSON;
		if (respuesta != undefined)
		{
			var ultimoId = this.ultimoId;
			var numLeidas = this.numLeidas;
			this.noLeidas = 0;
			this.notificaciones = respuesta.notificaciones;
			for (var i = 0; i < this.notificaciones.length; i++)
			{
				if (!this.notificaciones[i].leido) this.noLeidas++;
				if (this.notificaciones[i].idNotificacion > this.ultimoId) this.ultimoId = this.notificaciones[i].idNotificacion;
			}
			this.actualizarNumNotificaciones ();
			if (this.ultimoId == ultimoId && this.numLeidas == numLeidas)
			{
				this.intervaloActualizacion = this.intervaloActualizacion * 2;
				if (this.intervaloActualizacion > 600000) this.intervaloActualizacion = 600000;
			}
			else this.intervaloActualizacion = 10000;
			this.iniciarTemporizador ();
			if (this.generada) this.generarListado ();
		}
	},

	descargarError: function ()
	{
		if (this.generada) this.error.removeClassName ("ocultar");
	},
	
	descargaFinalizada: function ()
	{
		if (this.generada) this.cargando.addClassName ("ocultar");
	},

	actualizarNumNotificaciones: function ()
	{
		this.numNotificaciones.innerHTML = this.noLeidas;
		if (this.noLeidas > 0)
		{
			this.botonNotificaciones.down ("img").src = rutaImagenes + "web/iconoUsuarioNotificacionesOn.png";
			this.numNotificaciones.removeClassName ("ocultar");
			document.title = "(" + this.noLeidas + ") " + this.tituloPagina;
		}
		else
		{
			this.botonNotificaciones.down ("img").src = rutaImagenes + "web/iconoUsuarioNotificaciones.png";
			this.numNotificaciones.addClassName ("ocultar");
			document.title = this.tituloPagina;
		}
	},

	iniciarTemporizador: function ()
	{
		this.detenerTemporizador ();
		this.temporizador = setTimeout (this.funcionDescargar, this.intervaloActualizacion);
	},

	detenerTemporizador: function ()
	{
		if (this.temporizador != null)
		{
			clearTimeout (this.temporizador);
			this.temporizador = null;
		}
	}
};

var notificacion = Class.create (
{
	ventana: null,
	idNotificacion: 0,
	tipo: "",
	id: "",
	leido: false,
	fecha: null,
	elemento: null,

	enlaceMarcarLeida: null,
	enlaceMarcarNoLeida: null,
	enlaceExcluir: null,
	enlaceBorrar: null,

	initialize: function (ventana, datos)
	{
		this.ventana = ventana;
		this.idNotificacion = datos.idNotificacion;
		this.tipo = datos.tipo;
		this.id = datos.id;
		this.leido = datos.leido;
		this.fecha = new Date (datos.fecha);

		var texto;
		var informacionExtra;
		this.elemento = Builder.node ("li",
		[
			texto = Builder.node ("p", {className: "texto"}),
			informacionExtra = Builder.node ("p", {className: "texto"}),
			Builder.node ("p", {className: "fecha"}, this.distancia ()),
			Builder.node ("div", {className: "enlaces"},
			[
				this.enlaceMarcarLeida = Builder.node ("a", {className: "ocultar"}, "Marcar como leída"),
				this.enlaceMarcarNoLeida = Builder.node ("a", {className: "ocultar"}, "Marcar como no leída"),
				" | ",
				this.enlaceExcluir = Builder.node ("a", "Excluir"),
				" | ",
				this.enlaceBorrar = Builder.node ("a", "Borrar")
			])
		]);
		if (this.leido) this.enlaceMarcarNoLeida.removeClassName ("ocultar");
		else
		{
			this.elemento.addClassName ("nueva");
			this.enlaceMarcarLeida.removeClassName ("ocultar");
		}
		texto.innerHTML = datos.texto;
		if (datos.informacionExtra.length > 0) texto.innerHTML += "<br /><span class=\"informacionExtra\">" + datos.informacionExtra + "</span>";

		this.enlaceMarcarLeida.observe ("click", this.marcarLeida.bind (this));
		this.enlaceMarcarNoLeida.observe ("click", this.marcarNoLeida.bind (this));
		this.enlaceExcluir.observe ("click", this.excluir.bind (this));
		this.enlaceBorrar.observe ("click", this.borrar.bind (this));

		this.ventana.lista.appendChild (this.elemento);
	},
	
	distancia: function ()
	{
		var ahora = new Date ().getTime ();
		var distancia = Math.round ((ahora - this.fecha.getTime ()) / 1000);
			
		if (distancia > 172800) distancia = this.fecha.getDate () + "/" + (this.fecha.getMonth () + 1) + "/" + this.fecha.getFullYear () + " " + this.fecha.getHours () + ":" + this.fecha.getMinutes ();
		else if (distancia > 3600)
		{
			var horas = Math.round (distancia / 3600);
			distancia = "Hace " + horas + " hora" + (horas == 1? "": "s");
		}
		else if (distancia > 60)
		{
			var minutos = Math.round (distancia / 60);
			distancia = "Hace " + minutos + " minuto" + (minutos == 1? "": "s");
		}
		else distancia = "Hace " + distancia + " segundo" + (distancia == 1? "": "s");

		return distancia;
	},

	marcarLeida: function ()
	{
		var yo = this;
		new Ajax.Request ("/notificacionLeida.jsp", {method: "get", parameters: {idNotificacion: this.idNotificacion},
			onSuccess: function (transport)
			{
				yo.ventana.noLeidas--;
				yo.ventana.actualizarNumNotificaciones ();
				yo.elemento.removeClassName ("nueva");
				yo.enlaceMarcarLeida.addClassName ("ocultar");
				yo.enlaceMarcarNoLeida.removeClassName ("ocultar");
			}
		});
	},
	
	marcarNoLeida: function ()
	{
		var yo = this;
		new Ajax.Request ("/notificacionNoLeida.jsp", {method: "get", parameters: {idNotificacion: this.idNotificacion},
			onSuccess: function (transport)
			{
				yo.ventana.noLeidas++;
				yo.ventana.actualizarNumNotificaciones ();
				yo.elemento.addClassName ("nueva");
				yo.enlaceMarcarNoLeida.addClassName ("ocultar");
				yo.enlaceMarcarLeida.removeClassName ("ocultar");
			}
		});
	},
	
	excluir: function ()
	{
		var yo = this;
		new Ajax.Request ("/notificacionExcluida.jsp", {method: "get", parameters: {id: this.id, tipo: this.tipo, excluir: "true"},
			onSuccess: function (transport)
			{
				yo.ventana.descargarNotificaciones ();
			}
		});
	},
	
	borrar: function ()
	{
		var yo = this;
		new Ajax.Request ("/borrarNotificacion.jsp", {method: "get", parameters: {idNotificacion: this.idNotificacion},
			onSuccess: function (transport)
			{
				if (!this.leido)
				{
					yo.ventana.noLeidas--;
					yo.ventana.actualizarNumNotificaciones ();
				}
				yo.elemento.addClassName ("ocultar");
			}
		});
	},

	quitar: function ()
	{
		this.enlaceMarcarLeida.stopObserving ("click");
		this.enlaceMarcarNoLeida.stopObserving ("click");
		this.enlaceExcluir.stopObserving ("click");
		this.enlaceBorrar.stopObserving ("click");

		this.elemento.remove ();
		this.elemento = null;
	}
});

function obtenerVideoEmbed (URL)
{
	var salida = {url: "", ancho: 0, alto: 0, flash: true};
	
	var partes = URL.match (/(.+).youtube.com\/watch?(.*)v=([^&]+)&?(.*)/i);
	if (partes == null) partes = URL.match (/(.+).youtu.be([\/])(.*)&?(.*)/i);
	if (partes != null)
	{
		partes[3] = partes[3].replace (/([xX])(D)/g, "$1%44");
		partes[3] = partes[3].replace (/([xX])(d)/g, "$1%64");
		salida.url = "http://www.youtube.com/embed/" + partes[3] + "?hd=1";
		salida.flash = false;
		salida.ancho = 830;
		salida.alto = 502;
		
		var pagina = window.location.href;
		if (pagina.match (/viciojuegos.com\/(nuevaNoticia.jsp|editarNoticia.jsp)(.*)/i) != null)
		{
			salida.ancho = 500;
			salida.alto = 314;
		}
		
		if (pagina.match (/viciojuegos.com\/(nuevaPaginaCritica.jsp|editarPaginaCritica.jsp|nuevaPaginaAvance.jsp|editarPaginaAvance.jsp|nuevaPaginaReportaje.jsp|editarPaginaReportaje.jsp|nuevaPaginaGuia.jsp|editarPaginaGuia.jsp)(.*)/i) != null)
		{
			salida.ancho = 550;
			salida.alto = 343;
		}
	}

	partes = URL.match (/(.+).gametrailers.com\/(video|user-movie)\/(.+)\/(.+)/i);
	if (partes != null)
	{
		salida.url = "http://media.mtvnservices.com/mgid:moses:" + (partes[2]=="video"? "video": "usermovie") + ":gametrailers.com:" + partes[4];
		salida.ancho = 512;
		salida.alto = 288;
	}

	partes = URL.match (/(.+).vimeo.com\/(.+)/i);
	if (partes != null)
	{
		salida.url = "http://player.vimeo.com/video/" + partes[2] + "?title=0&amp;byline=0&amp;portrait=0";
		salida.flash = false;
		salida.ancho = 830;
		salida.alto = 467;
	}
	
	partes = URL.match (/(.+).metacafe.com\/watch\/(.+)\/(.*)\//i);
	if (partes != null)
	{
		salida.url = "http://www.metacafe.com/fplayer/" + partes[2] + "/" + partes[3] + ".swf";
		salida.ancho = 600;
		salida.alto = 370;
	}
	
	partes = URL.match (/(.+).twitvid.com\/(.*)/i);
	if (partes != null)
	{
		salida.url = "http://www.twitvid.com/embed.php?guid=" + partes[2] + "&autoplay=0";
		salida.flash = false;
		salida.ancho = 480;
		salida.alto = 360;
	}
	
	partes = URL.match (/(.+).dailymotion.com\/video\/(.*)_(.*)/i);
	if (partes != null)
	{
		salida.url = "http://www.dailymotion.com/embed/video/" + partes[2];
		salida.flash = false;
		salida.ancho = 560;
		salida.alto = 315;
	}
	
	return salida;
}

function insertarVideo (capa, url, ancho, alto)
{
	var infoVideo = obtenerVideoEmbed (url);
	if (infoVideo.url == "") return false;
	
	if (ancho > infoVideo.ancho)
	{
		var relacion = infoVideo.ancho / infoVideo.alto;
		ancho = infoVideo.ancho;
		alto = Math.round (ancho / relacion);
	}

	if (infoVideo.flash) swfobject.embedSWF (infoVideo.url, capa, ancho, alto, "10.0", null, null, null);
	else $(capa).appendChild (Builder.node ("iframe", {src: infoVideo.url, frameborder: 0, scrolling: "no", style: "width: " + ancho + "px; height: " + alto + "px;"}));
}

function tunearEnlace (enlace)
{
	if (!enlace.hasClassName ("botonTuneadoJS") && VersionIE > 0 && VersionIE < 10)
	{
		enlace.addClassName ("botonTuneadoJS");
		var Texto = enlace.innerHTML;
		var Ancho = enlace.getWidth ();
		enlace.innerHTML = "";
		enlace.appendChild (Builder.node ("span", {className: "i"}));
		enlace.appendChild (Builder.node ("span", {className: "c", style: "width: " + (Ancho - 19) + "px;"}, Texto));
		enlace.appendChild (Builder.node ("span", {className: "d"}));
	}
}

function inicializarControles ()
{
	$$("a").each (function (enlace)
	{
		if (enlace.hasClassName ("botonTuneado")) tunearEnlace (enlace);
		if (enlace.href.match(/(.+).viciojuegos.com\/juego\/(.+)\/(.+)\/([0-9]+)/i) || enlace.href.match(/(.+).viciojuegos.com\/juego.jsp?(.*)idJuego=([0-9]+)&?(.*)/i)) new enlaceJuego (enlace);
		if (enlace.href.match(/(.+).viciojuegos.com\/fichaUsuario.jsp?(.*)nick=(.+)&?(.*)/i)) new enlaceUsuario (enlace);
		if (enlace.rel == "lightbox") new lightboxImagen (enlace);
		if (enlace.rel == "lightboxVideo") new lightboxVideo (enlace);
	});

	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].type=="text" && inputs[i].className.indexOf("marcaAguaTexto")>=0) new marcaAguaTexto (inputs[i]);
		if (inputs[i].type=="text" && inputs[i].className.indexOf("selectorFecha")>=0) new SelectorFecha(inputs[i]);
	}

	var selects = Element.select (document, "select.selectTuneado");
    for (var i = 0; i < selects.length; i++) if (selects[i].className.indexOf("selectTuneado") >= 0) new selectTuneado(selects[i]);
	
	selects = Element.select (document, "select.selectMultiple");
    for (var i = 0; i < selects.length; i++) if (selects[i].className.indexOf("selectMultiple") >= 0) new selectMultiple(selects[i]);

	lightbox.generar ();
	ventanaNotificaciones.inicializar ("botonNotificaciones");
}

var VersionIE = Prototype.Browser.IE? parseInt (navigator.appVersion.substring (navigator.appVersion.indexOf ("MSIE ") + 5)): 0;
var dialogo = new dialogoBase ();
