

// Evento onload de windows para anyadir eventos a los campos 
Event.observe( window, 'load', attachNameChecker );
// A ejecutar cuando se haya cargado la pagina
function attachNameChecker(){
	// observamos cuando se suelta un tecla para ejacutar checkname()
	Event.observe( $( 'usuario_fotoblog' ), 'keyup', checkName );
	// Anyadimos controles para index.php
	if( $( 'freg' ) ){
		// Deshabilitamos el boton de crear fotoblog
		$( 'freg' ).getElementsByTagName( 'input' )[1].disabled = true;
		// Observamos si se envia el form de crear fotoblog
		Event.observe( 'freg', 'submit', checkIndexSubmit );
	}
}
// A ejecutar cuando se envia el form de crear fotoblog en index.php
function checkIndexSubmit( evt ){
	if( Element.hasClassName( $( 'usuario_fotoblog'), 'not-valid' ) || !$F( 'usuario_fotoblog') ){
		return false;
	}
	return true;
}
// Envia los caracteres del campo usuario al server para ser chequeado
function checkName(){
	var postData = 'name=' + encodeURIComponent( $F( 'usuario_fotoblog' ) );
	new Ajax.Request( '/includes/ajax_check_name.php', {method:'post',postBody: postData, onSuccess: nameChecked} );
	if( $F( 'usuario_fotoblog' ) ){
		Element.update( $( 'theUser' ), $F( 'usuario_fotoblog' ) );
	}else{
		Element.update( $( 'theUser' ), 'usuario' );
	}
}
// Recibe la respuesta del servidor
function nameChecked( r ){
	if( r.responseText == 'OK' ){
		Element.setStyle( $( 'usuario_fotoblog' ), {borderColor:'#009900'} );
		Element.update( $( 'usuario_message' ), '' );
		Element.removeClassName( $( 'usuario_fotoblog' ), 'not-valid' );
		if( $( 'freg' ) ){
			$( 'freg' ).getElementsByTagName( 'input' )[1].disabled = false;
		}
	}else{
		Element.setStyle( $( 'usuario_fotoblog' ), {borderColor:'#ff0000'} );
		Element.update( $( 'usuario_message' ), r.responseText );
		Element.addClassName( $( 'usuario_fotoblog' ), 'not-valid' );
		if( $( 'freg' ) ){
			$( 'freg' ).getElementsByTagName( 'input' )[1].disabled = true;
		}
	}
}
