// Se revisan todos los formularios del documento, así como todos los campos que vamos
// a controlar mediante este script.

TextoForms = {
	inputs : document.getElementsByTagName("input"),
	textareas : document.getElementsByTagName("textarea"),
	
	// Guardamos los valores iniciales
	valorinicial : new Array(),
	
	associateObjWithEvent : function(obj, methodName) {
		return (function(e) {
			e = e||window.event;
			return obj[methodName](e, this);
		});
	},
	
	// 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.
	run : function() {
		for (var i = 0; i < this.inputs.length; i++) {
			if ((this.inputs[i].type == "text") || (this.inputs[i].type == "password")) { 
				this.valorinicial[this.inputs[i].id] = this.inputs[i].value;
				this.inputs[i].onfocus = function() { TextoForms.vacia(this.id,this.value) }
				this.inputs[i].onblur = function() { TextoForms.restaura(this.id,this.value) }
			}
		}
		for (var i = 0; i < this.textareas.length; i++) { 
			this.valorinicial[this.textareas[i].id] = this.textareas[i].value;
			this.textareas[i].onfocus = function() { TextoForms.vacia(this.id,this.value) }
			this.textareas[i].onblur = function() { TextoForms.restaura(this.id,this.value) }
		}
	},
	
	// Vaciamos los campos únicamente cuando su contenido sea el mismo que el inicial
	vacia : function (id,valor) {
	    var targetElement = $$(id);
		var tipo = targetElement.type;
		switch ( tipo ) { 
			case "text":
				if (this.valorinicial[id] == valor)
					targetElement.value = "";
				break
			case "password":
				if (this.valorinicial[id] == valor)
					targetElement.value = "";
				break
			case "textarea":
				if (this.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
	restaura : function(id) {
	    var targetElement = $$(id);
		var tipo = targetElement.type;
		switch ( tipo ) { 
			case "text":
				if (targetElement.value.replace(/ /g, '') == '')
					targetElement.value = this.valorinicial[id];
					break
			case "password":
				if (targetElement.value.replace(/ /g, '') == '')
					targetElement.value = this.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 = this.valorinicial[id];
					targetElement.value = this.valorinicial[id];
				}
				break
		}
	}
}

