/*	Field es una clase que representa la columna de una tabla de base de datos
 *
 */


/* Constructor
 * Se encarga de  construir el objeto con los datos que nos ofrece la BD sobre una field de una tabla
 *
 * name:	Nombre de la field
 * type:	Tipo de la field (int, blob, real...)
 * len:		Longitud.
 * flags:	Etiquetas (not_null, primary_key ...)
 * table:	Tabla a la que pertenece (en esta práctica eso no nos importa).
 */
function Field(name, type, len, flags, table)
{
	// Inicializa los datos
	this.name = name;
	this.type = type;
	this.len = len;
	this.flags = flags;
	this.table = table;

	this.settings = 
	{
		data:
		{
			name:				this.name,
			reg_exp:			false,
			type:				false,

			select_values:		false
		},


		input:
		{
			class_names:
			{
				div_cell:		"",
				div_title:		"",
				div_input:		"",
				div_error:		""
			},

			contents:
			{
				div_cell:		false,
				div_title:		false,
				div_error:		false
			}
		},

		output:
		{
			class_names:
			{
				div_cell:		"",
				div_title:		"",
				div_value:		""
			},

			contents:
			{
				div_cell:		false,
				div_title:		false,
				div_value:		false
			}
		}
	}

	this.def_error = 
	{
		cells:				false,
		func:				false,
		text:				false
	}

	if(type == "int")
		this.settings.data.reg_exp = /^(?:\+|-)?\d+$/;
	else if(type == "real")
		this.settings.data.reg_exp = /^(?:\+|-)?\d+\.\d*$/g;

}

Field.prototype = 
{
	/* Esta función sirve para configurar una field y darle valores
	 * El único parámetro que le pasemos será un JSON con toda la confiuración de la field:
	 *
	 * data: 			JSON con la configuración:
	 * 		def_name:		Nombre que se va a mostrar
	 * 		def_type:		Tipo de input (password, text. ..)
	 * 		regexp:			Expresión regular asociada.
	 * 		opt_values:		Valores en caso de ser un select
	 * 		hide_name:		Ocultar el nombre?
	 * 		hidden:			Ocular field?
	 */
	setup: function(data)
	{
		var res = "";

		if(data)
		{
			for(var lv1 in this.settings)
			{
				if(data[lv1])
				{
					for(var lv2 in this.settings[lv1])
					{
						if(data[lv1][lv2])
						{
							if(lv1 == "data")
								this.settings[lv1][lv2] = data[lv1][lv2];
							else
							{
								for(var lv3 in this.settings[lv1][lv2])
								{
									if(data[lv1][lv2][lv3])
									{
										this.settings[lv1][lv2][lv3] = data[lv1][lv2][lv3];
									}
								}
							}
						}
					}
				}
			}
		}
	},


	loadDefaults:	function(def_conf)
	{
		var res = "";

		for(var lv1 in this.settings)
		{
			if(lv1 != "data")
			{
				for(var lv2 in this.settings[lv1])
				{
					for(var lv3 in this.settings[lv1][lv2])
					{
						if(!this.settings[lv1][lv2][lv3])
						{
							if(def_conf && def_conf[lv1] && def_conf[lv1][lv2] && def_conf[lv1][lv2][lv3])
								res = def_conf[lv1][lv2][lv3];
							else
							{
								if(lv2 == "contents")
									res = document.createElement("div");
							}

							this.settings[lv1][lv2][lv3] = res;


						}
					}
				}
			}
		}
	},


	/* Asocia una función de erro de usuario
	 *
	 * cells:	Cells implicadas
	 * func:	Función que se tiene que cumplir (func(cells[0] -> cells[1]) == 1) -> OK
	 */
	setErrorFunc: function(cells, func, text)
	{
		this.def_error.cells = cells;
		this.def_error.func = func;
		this.def_error.text = text;
	},

	isPrimKey: function()
	{
		return (/.*primary_key.*$/.test(this.flags));
	},
	
	isNotNull: function()
	{
		return (/.*not_null.*$/.test(this.flags));
	},

	/* Crea el input, según el tipo
	 * De momento sólo pueden crearse de tipo blob (textarea de muchos datos)
	 * y de tipo input -> text, password, para menos datos.
	 */
	getInput: function(cell)
	{
		var input = false;

		// Radio y Select
		if(this.settings.data.type && this.settings.data.select_values)
		{
			if(this.settings.data.type == "select")
			{
				input = document.createElement("select");
				input.className = this.settings.input.class_names.div_input;
				var option;

				for(var n in this.settings.data.select_values)
				{
					option = document.createElement("option");
					option.setAttribute("value", n)
					option.appendChild(document.createTextNode(this.settings.data.select_values[n]));

					input.appendChild(option);
				}
			}
			else if(this.settings.data.type == "radio")
			{
				var input = document.createElement("div");
				input.className = this.settings.input.class_names.div_input;
				var option;

				for(var n in this.settings.data.select_values)
				{
					option = document.createElement("input");
					option.setAttribute("type", "radio");
					option.setAttribute("value", n);
					option.setAttribute("name", this.name);
					option.style.marginRight = "25px";

					input.appendChild(document.createTextNode(this.settings.data.select_values[n]));
					input.appendChild(option);
				}
			}
		}
		else
		{
			if(this.type == "blob")
			{
				input = document.createElement("textarea");
				input.className = this.settings.input.class_names.div_input;
				input.rows = "15";
			}
			else
			{
				input = document.createElement("input");
				input.className = this.settings.input.class_names.div_input;

				if(this.settings.data.type)
				{
					input.setAttribute("type", this.settings.data.type);
					input.value = 0;
				}
					
				else
					input.setAttribute("type", "text");
			}
		}


		// EH
		var self = this;
		if(this.settings.data.type == "radio" || this.settings.data.type == "checkbox" || this.settings.data.type == "select")
		{
			EH.addEventHandler(input, "click", function()
			{
				if(self.settings.data.type == "radio")
					input.value = EH.getEvent().target.getAttribute("value");

				else if(self.settings.data.type == "checkbox")
					input.value = input.checked == true ? 1 : 0;

				cell.setError(false, false);

				if(cell.timeout)
					clearTimeout(cell.timeout);

				cell.timeout = setTimeout(function() { cell.check() }, 1 );
			} );
		}
		else
		{
			EH.addEventHandler(input, "keydown", function()
			{
				cell.setError(false, false);

				if(cell.timeout)
					clearTimeout(cell.timeout);

				cell.timeout = setTimeout(function() { cell.check() }, 500 );
			} );
		}
		
		return input;
	}
}



