/*
Autor: http://www.niquelao.net
Puedes utilizar líbremente este script respetando estas línea de comentarios.
También puedes modificarlo líbremente. Cualquier mejora será bienvenida.
*/
// Se revisan todos los formularios del documento, así como todos los campos que vamos
// a controlar mediante este script.
var forms =  document.getElementsByTagName("form");
var inputs = document.getElementsByTagName("input");
var textareas =  document.getElementsByTagName("textarea");

// Guardamos los valores iniciales
var valorinicial = new Array();

// Esta función asigna a los campos en los que se puede introducir texto las funciones
// necesarias para vaciar su contenido o restaurarlo al original según las circunstancias.
function formulario() {
	for (var i = 0; i < inputs.length; i++) {
		if((inputs[i].type == "text") || (inputs[i].type == "password")) { 
			valorinicial[inputs[i].id]=inputs[i].value;
			inputs[i].onfocus = function() {vacia(this.id,this.value)}
			inputs[i].onblur = function() {restaura(this.id,this.value)}
		}
	}
	for (var i = 0; i < textareas.length; i++) { 
		valorinicial[textareas[i].id]=textareas[i].value;
		textareas[i].onfocus = function() {vacia(this.id,this.value)}
		textareas[i].onblur = function() {restaura(this.id,this.value)}
	}
}

// Vaciamos los campos únicamente cuando su contenido sea el mismo que el inicial
function vacia(id,valor){
    var targetElement = document.getElementById(id);
	var tipo = targetElement.type;
	switch ( tipo ) { 
		case "text":
			if (valorinicial[id] == valor)
				targetElement.value = "";
			break
		case "password":
			if (valorinicial[id] == valor)
				targetElement.value = "";
			break
		case "textarea":
			if (valorinicial[id] == valor) {
				targetElement.innerHTML = "";
				targetElement.value = "";
			}
			break
	}
}

//Restauramos el contenido de los campos en el caso
// de no haber introducido nada o úncicamente espacios en blanco
function restaura(id){
    var targetElement = document.getElementById(id);
	var tipo = targetElement.type;
	switch ( tipo ) { 
		case "text":
			if (targetElement.value.replace(/ /g, '') == '')
				targetElement.value = valorinicial[id];
				break
		case "password":
			if (targetElement.value.replace(/ /g, '') == '')
				targetElement.value = valorinicial[id];
				break
		case "textarea":
			revisa = targetElement.value.replace(/ /g, '');
			// Eliminamos saltos de l�nea y tabulaciones
			revisa = revisa.replace(/\n/g, '')
			revisa = revisa.replace(/\t/g, '')
			revisa = revisa.replace(/\r/g, '')
			if (revisa == '') {
				targetElement.innerHTML = valorinicial[id];
				targetElement.value = valorinicial[id];
			}
			break
	}
}

//guarda el evento onLoad en nuestro manejador
setOnLoad('formulario');

