/* Este archivo contiene la clase Form, que permite crear un formulario a partir de un div y una serie de fields
 * Conviene ver la documentación de Cell y Form antes.
 */

/* Constructor
 * Este constructor sólo requiere un div padre que lo contenga y las fields asociadas.
 */
function Form(parent_div_id, fields, groups, def_conf)
{
	this.parent_div_id = parent_div_id;

	this.parent_div  = false;
	this.div_content = false;
	this.fields = fields;
	
	this.groups = groups;
	this.cells = new Array;

	this.setup(def_conf);
	this.create();

}


Form.prototype = 
	{
		/* Crea el formulario
		 * Para ello crea una cell para cada field y le asigna el nombre de la field y un id único.
		 */

		setup:	function(def_conf)
		{
			var par = true;
			for(var f in this.fields)
			{
				if(par)
					this.fields[f].loadDefaults(def_conf.par);
				else
					this.fields[f].loadDefaults(def_conf.impar);

				par = !par;
			}
		},
		
		create:	function()
		{
			this.div_content = document.createElement("div");

			for(var i = 0; i < this.fields.length; i++)
			{
				this.cells[i] = new Cell(this.div_content, this.fields[i]);
			}

			

		},

		/* Esta función muestra todos los cells
		 * Para ello llama a cell.show de cada Cell. También crea un botón Submit.
		 * Por ahora dicho botón no hace nada especial, sólo cambia el modo de mostrar de IN a OUT.
		 * En la siguiente práctica seguramente tenga que actualizar la BD.
		 *
		 * type:	Es el modo que queremos mostrar cada cell (IN / OUT)
		 */
		show:	function(type)
		{
			this.parent_div = document.getElementById(this.parent_div_id);

			if(this.parent_div)
			{
				var normal = false;
				var className;

				this.parent_div.appendChild(this.div_content);

				// Mostrar Cells
				for(var i in this.cells)
				{
					if(normal)
						className = "nonselected_field";
					else
						className = "selected_field";

					normal = !normal;
					this.cells[i].show(type, className);
				}

				// Si Type es IN, crear el Submit
				if(type == "input")
				{
					var div_submit = document.createElement("input");

					div_submit.setAttribute("type", "button");
					div_submit.setAttribute("value", "Submit");
					div_submit.setAttribute("id", this.parent_div.getAttribute("id") + "_submit");

					var self = this;

					EH.addEventHandler(div_submit, "click", function(ev) { self.submit(ev); }, 100);
					this.parent_div.appendChild(div_submit);
				}
				// Si es OUT y el botón SUBMIT estaba creado (de shows anteriores), borrarlo.
				else if(document.getElementById(this.parent_div.getAttribute("id") + "_submit"))
				{
					this.parent_div.removeChild(document.getElementById(this.parent_div.getAttribute("id") + "_submit"));
				}
			}

		},

		// Crea una función de error de usuario asociada a la field indicada.
		setErrorFunc: function(fields, func, text)
		{
			var cells = new Array();
			if(fields.length)
			{
				var f;

				for(f in fields)
				{
					if(this.cells[fields[f]])
						cells.push(this.cells[fields[f]]);
				}

				for(f in fields)
				{
					if(this.fields[fields[f]])
						this.fields[fields[f]].setErrorFunc(cells, func, text);
				}

			}
		},

		/* Esta función se llamará cuando pulsemos el botón submit
		 * De momento comprobará que todos los cells son correctos (check) y luego mostrará de modo OUT.
		 */
		submit:	function()
		{
			var event = EH.getEvent();
			var i;

			if(EH.getActive(event.target))
			{
				var res = 0;
				for(i in this.cells)
					res += this.cells[i].check();

				if(res == 0)
				{
					var str = "<br/><hr/>"
					for(i in this.cells)
					{
						this.cells[i].value = this.cells[i].new_value;
						str += this.cells[i].field.settings.def_name + ": " + this.cells[i].value + "<br/><hr/>";
					}

					MessageBox(false, "Enviando petición", "En realidad no hay petición ni nada, no te hagas líos: " + str, false);
					this.show("out");
				}
			}


		},


		erase:		function()
		{
			while(this.parent_div.firstChild)
				this.parent_div.removeChild(this.parent_div.firstChild);
		}
	}

		

		

