function createBackgroundLogin() {
	var ancho = window.getWidth();
	var alto = window.getHeight();
	var cortina = new Element('div').setProperties({
		'id' : 'cortinaFondo'
	}).setStyles({
		'position' : 'absolute',
		'top' : '0px',
		'left' : '0px',
		'width' : ancho + 'px',
		'height' : alto + 'px',
		'z-index' : '100000',
		'background-color' : '#000',
		'opacity' : 0
	}).addEvent('click', function() {delLogin();return false;}).injectInside(document.body);
	cortina.effect('opacity', {'transition': Fx.Transitions.quadOut, 'duration' : 800}).start(0,0.5);

}

function removeCortina() {
	$('cortinaFondo').remove();
}

function removeLoginWindow() {
	$('ventana').remove();
}

function delLogin() {
	$('cortinaFondo').effect('opacity', {transition : Fx.Transitions.quadOut, 'duration' : 800}).start(0.5, 0);
	removeCortina.delay(850);
	$('ventana').effect('opacity', {transition : Fx.Transitions.quadOut, 'duration' : 800}).start(1, 0);
	removeLoginWindow.delay(850);
}
/**/
function prevAddPass(lang) {

	createBackgroundLogin();	

	var x = (window.getWidth() / 2) - 135;
	var y = (window.getHeight() / 3) - 120;
	var ancho = 270;
	var alto = 160;
	var contenedor = new Element('div').setProperties({
		'id' : 'ventana'
	}).setStyles({
		'position' : 'absolute',
		'top' : y + 'px',
		'left' : x + 'px',
		'width' : ancho + 'px',
		'height' : alto + 'px',
		'z-index' : '100001',
		'background-color' : '#fff',
		'opacity' : 0,
		'padding' : '10px',
		'text-align' : 'left'
	});

	new Ajax('/src/getCamposPass.php', {
			'method' : 'post',
			'postBody'   : 'lang=' + lang,
			'onComplete' : function(text,xml) {handleEnvioRequest(xml, 'create', contenedor, lang)}
		}).request();
	
	contenedor.injectInside(document.body).effect('opacity', {transition : Fx.Transitions.linear, 'duration' : 500}).start(0, 1);

}

function prevAddLogin(lang) {

	createBackgroundLogin();
	var x = (window.getWidth() / 2) - 135;
	var y = (window.getHeight() / 3) - 120;
	var ancho = 270;
	var alto = 160;
	var contenedor = new Element('div').setProperties({
		'id' : 'ventana'
	}).setStyles({
		'position' : 'absolute',
		'top' : y + 'px',
		'left' : x + 'px',
		'width' : ancho + 'px',
		'height' : alto + 'px',
		'z-index' : '100001',
		'background-color' : '#fff',
		'opacity' : 0,
		'padding' : '10px',
		'text-align' : 'left'
	});
	
	new Ajax('/src/getCamposRegistro.php', {
			'method' : 'post',
			'postBody'   : 'lang=' + lang,
			'onComplete' : function(text,xml) {handleEnvioRequest(xml, 'create', contenedor,lang)}
		}).request();
	
	contenedor.injectInside(document.body).effect('opacity', {transition : Fx.Transitions.linear, 'duration' : 500}).start(0, 1);
}


function sendEnvioRequest(type, lang) {

	if(type == 'new') {		
		var params = myToQueryString($('ventana'));
		new Ajax('/src/getCamposRegistro.php?comprobar=1', {
			'method' : 'post', 
			'postBody' : params,
			'onComplete' : function(text, xml) {handleEnvioRequest(xml, 'request', $('ventana'), lang)}
		}).request();
	}
	else if(type == 'pass') {
		//***
		var params = myToQueryString($('ventana'));  
         
		new Ajax('/src/getCamposPass.php?comprobar=1&lang=' + lang, {
			'method' : 'post',
			'postBody'   : params,
			'onComplete' : function(text,xml) {handleEnvioRequest(xml, 'request', $('ventana'), lang)}
		}).request();
	}
	else if(type == 'create') {		
		new Ajax('/src/getCamposRegistro.php', {
			'method' : 'post',
			'postBody'   : 'lang=' + lang,
			'onComplete' : function(text,xml) {handleEnvioRequest(xml, 'create', $('ventana'), lang)}
		}).request();
		new Ajax('/src/getCamposPass.php', {
			'method' : 'post',
			'postBody'   : 'lang=' + lang,
			'onComplete' : function(text,xml) {handleEnvioRequest(xml, 'create', $('ventana'), lang)}
		}).request();
	}

}

function  handleEnvioRequest(xml, type, target, lang) {

	if(type == 'request') {
		handleEnvio(xml.documentElement);
	}
	else if(type == 'create') {
		createForm(xml.documentElement, target, lang);
	}	
}



function createForm(xml, target, lang) {
	target.setHTML('');

	var errores = xml.firstChild;
	var lenguaje = lang;
	var campos = errores.nextSibling;
	var literal = campos.nextSibling;
	var olvido = literal.nextSibling;

	var form = new Element('form').addClass('formLogin');
	
	var field = new Element('fieldset');
	//new Element('legend').setHTML('Usuario registrado').injectInside(field);
	//new Element('legend').setHTML('<?= $IDIOMA[\'zona_usuario_registrado\'] ?>').injectInside(field);
	if(literal.childNodes.item(0).firstChild){
	new Element('legend').setHTML(literal.childNodes.item(0).firstChild.nodeValue).injectInside(field);
	}
	// Elementos
	var nEl = campos.childNodes.length;
	for(var i = 0; i < nEl; i++) {
		var noPassword = true;
		var este = campos.childNodes.item(i);
		var tipo = este.getAttribute('type');
		var etiqueta = new Element('label').setProperty('for', 'ENVIO_' + este.getAttribute('name')).setHTML(este.getAttribute('label'));
		if(tipo == 'input') {
			etiqueta.injectBefore(
				new Element('input').setProperties({
					'id' : 'PARTICIPA_' + este.getAttribute('name'),
					'name' : 'PARTICIPA[' + este.getAttribute('name') + ']',
					'type' : 'text',
					'value' : (este.firstChild)?este.firstChild.nodeValue:''
				}).injectBefore(new Element('br').injectInside(field))
			);		
		}
		else if(tipo == 'password') {
			etiqueta.injectBefore(
				new Element('input').setProperties({
					'id' : 'PARTICIPA_' + este.getAttribute('name'),
					'name' : 'PARTICIPA[' + este.getAttribute('name') + ']',
					'type' : 'password',
					'value' : (este.firstChild)?este.firstChild.nodeValue:''
				}).injectBefore(new Element('br').injectInside(field))
			);
			noPassword = false;			
		}
	}
	
	if(noPassword){
		new Element('input').setProperties({
			'class' : 'boton',
			'type' : 'button',
			'value' : 'continuar'
		}).addEvent('click', function() {sendEnvioRequest('pass', lang);return false;}).injectInside(
			new Element('p').injectInside(field)
		);			
	}
	else{
		new Element('input').setProperties({
			'class' : 'boton',
			'type' : 'button',
			'value' : 'continuar'
		}).addEvent('click', function() {sendEnvioRequest('new', lang);return false;}).injectInside(
			new Element('p').injectInside(field)
		);
	}
	field.injectInside(form);
	
	//target.injectInside(new Element('a').setHTML('[AÃºn no estoy registrado]'));
	//var a = new Element('a').setProperty('href', '<?= $urls[\'mi-cuenta\'] ?>').setHTML('<?= $IDIOMA[\'zona_aun_no_registro\'] ?>').injectInside(form)
	if(literal.childNodes.item(0).firstChild){
	var a = new Element('a').setProperty('href', literal.childNodes.item(1).firstChild.nodeValue).setHTML(literal.childNodes.item(2).firstChild.nodeValue).injectInside(form)
	}
	var b = new Element('a').setHTML(olvido.childNodes.item(2).firstChild.nodeValue).addEvent('click', function() {delLogin();prevAddPass(lenguaje);return false;}).injectInside(form)
	form.injectInside(target);
}

function handleEnvio(xml) {
	//alert('envio!!!!');
	//alert(xml);

	//si hay errores hacemos blick para que se den cuenta
	var errores = xml.firstChild;

	//var campos = errores.nextSibling;

	//alert(errores);
	// Elementos
	
	var nEl = errores.childNodes.length;
	if(nEl) {
		for(var i = 0; i < nEl; i++) {
			var este = errores.childNodes.item(i);
			//var tipo = este.getAttribute('type');
			
			//alert( este.getAttribute('id') );
			//alert(este.getAttribute('id'));
			var el = $('PARTICIPA_' + este.getAttribute('id'));
			
			//alert(el);
			//if(tipo == 'input' || tipo == 'password') {
				//alert(este);
				blinkProperty('border-color', el, '#f00', '#d4d4d4', 3);
			//}		
		}		
	} else {
		

		var urlDestino = window.location.href;
		//document.href = 'talparacual'+
		//alert("Todo OK")
		//document.href =
		//alert(location.href)
		//window.location = '<?= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>';
		//alert(window.location.href);


		if(urlDestino.indexOf("logout")>0){	
			window.location = urlDestino.replace(/\&?logout=1/, '');
		}
		else{
			window.location = urlDestino.replace(/\#/, '');
		}
		//alert(location.href.replace(/\&?logout=1/, ''));
	
	}
	//sino redireccionamos la pagina :-)
}

function myToQueryString(el) {
	//alert(el)

	var queryString = [];
	$$(el.getElementsByTagName('input'), el.getElementsByTagName('select'), el.getElementsByTagName('textarea')).each(function(act) {
		//alert(act.name);
		var id = act.id.toString();
		var value = act.value;
		var sal = id.match(/^([A-Z]+)_([a-zA-Z0-9_]+)$/);
		if(sal && sal.length == 3) {
			queryString.push(encodeURIComponent(sal[1] + '[' + sal[2] + ']')+'='+encodeURIComponent(value));
			//alert(sal[1] + '[' + sal[2] + '] = ' + act.value);
		}
	});
	return queryString.join('&');
}

function blinkProperty(prop, elName, from, to, veces) {
	//alert(elName);
	var duration = 500;
	var margin = 100;
	var colores = {'in' : new Color(from), 'out' : new Color(to)};
	var blink = new Fx.Style(elName, prop, {'duration': duration, 'transition': Fx.Transitions.linear});
	blink.start(colores['in'], colores['out']);
	for(var i = 0; i < veces; i++) {
		blink.start.pass([colores['out'], colores['in']], blink).delay((duration+margin) * ((i*2)+1));
		blink.start.pass([colores['out'], colores['in']], blink).delay((duration+margin) * ((i*2)+1));
	}
	blink.start.pass([colores['out'], colores['in']], blink).delay((duration+margin) * ((i*2)+1));
}

